Rating
<gui-rating> is a row of stars to give a score, such as a review’s. The stars are native radio
buttons, hidden on screen under drawn stars, so the keyboard and screen readers treat it as a
radio group. Its value is the number of stars picked.
import { GuiRating } from '@golemui/gui-components/react';import '@golemui/gui-components/index.css';
export function RatingBasic() { return <GuiRating label="Service" hint="How was your visit?" />;}import { Component, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';import '@golemui/gui-components/rating';
@Component({ selector: 'app-rating-basic', schemas: [CUSTOM_ELEMENTS_SCHEMA], template: ` <gui-rating label="Service" hint="How was your visit?"></gui-rating> `,})export class RatingBasicComponent {}<script setup lang="ts">import '@golemui/gui-components/rating';import '@golemui/gui-components/index.css';</script>
<template> <gui-rating label="Service" hint="How was your visit?"></gui-rating></template>import { LitElement, html } from 'lit';import { customElement } from 'lit/decorators.js';import '@golemui/gui-components/rating';import '@golemui/gui-components/index.css';
@customElement('rating-basic')export class RatingBasic extends LitElement { protected override createRenderRoot() { return this; }
override render() { return html` <gui-rating label="Service" hint="How was your visit?"></gui-rating> `; }}<gui-rating label="Service" hint="How was your visit?"></gui-rating>The element’s entry point is @golemui/gui-components/rating, which registers <gui-rating>
and nothing else. To install the package and load the stylesheet, see
Installation.
The @golemui/gui-components/react components have typed props and an on* prop for each event. React 18 or later.
import { useState } from 'react';import { GuiRating } from '@golemui/gui-components/react';import '@golemui/gui-components/index.css';
export function ServiceField() { const [service, setService] = useState(undefined as number | undefined);
return ( <GuiRating label="Service" name="service" value={service} onGuiChange={(event) => setService(event.detail.value ?? undefined as number | undefined)} /> );}Add CUSTOM_ELEMENTS_SCHEMA to the component that uses the tags, and the stylesheet to styles in angular.json.
import { Component, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';import type { GuiEventMap, GuiRatingEvents } from '@golemui/gui-components';import '@golemui/gui-components/rating';
type ChangeEvent = GuiEventMap<typeof GuiRatingEvents>['gui-change'];
@Component({ selector: 'app-service-field', schemas: [CUSTOM_ELEMENTS_SCHEMA], template: ` <gui-rating label="Service" name="service" [value]="service" (gui-change)="onChange($event)" ></gui-rating> `,})export class ServiceFieldComponent { service = undefined as number | undefined;
onChange(event: Event) { this.service = (event as ChangeEvent).detail.value ?? undefined as number | undefined; }}"styles": ["node_modules/@golemui/gui-components/lib/styles/index.css"]Tell Vue's compiler that gui-* tags are custom elements, and add the typings once for typed props and @gui-* handlers.
<script setup lang="ts">import { ref } from 'vue';import '@golemui/gui-components/rating';import '@golemui/gui-components/index.css';
const service = ref(undefined as number | undefined);</script>
<template> <gui-rating label="Service" name="service" :value="service" @gui-change="service = $event.detail.value ?? undefined as number | undefined" /></template>vue({ template: { compilerOptions: { isCustomElement: (tag) => tag.startsWith('gui-') } },});import type {} from '@golemui/gui-components/vue';The page's stylesheet styles the gui-* elements, so it only reaches them outside a shadow root. Render the host component into the light DOM too, as below, or load the stylesheet into its shadow root.
import { LitElement, html } from 'lit';import { customElement, state } from 'lit/decorators.js';import '@golemui/gui-components/rating';import '@golemui/gui-components/index.css';
@customElement('service-field')export class ServiceField extends LitElement { @state() private service = undefined as number | undefined;
protected override createRenderRoot() { return this; }
override render() { return html` <gui-rating label="Service" name="service" .value=${this.service} @gui-change=${(event: CustomEvent) => (this.service = event.detail.value)} ></gui-rating> `; }}With any bundler, such as Vite. Import the element once, anywhere, and use the tag in your markup.
<gui-rating label="Service" name="service"></gui-rating>
<script type="module" src="./main.js"></script>import '@golemui/gui-components/rating';import '@golemui/gui-components/index.css';
const element = document.querySelector('gui-rating');
element.addEventListener('gui-change', (event) => { console.log(event.detail.value);});Properties
| Property | Type | Default | Description |
|---|---|---|---|
value | number | – | The number of stars picked, from 1 to max, or undefined before the user picks one. |
max | number | 5 | How many stars it has. Defaults to 5. |
uid | string | – | The id of the element's control. The ids of its label, hint and errors derive from it. Optional: when it is not set, the element generates one from its tag name and a page-wide counter, e.g. gui-textinput-3. Generated ids depend on creation order, so a server-rendered element must set uid or its ids will not match after hydration. |
idPrefix
attribute id-prefix | string | – | Goes in front of every DOM id the element renders, so two elements with the same uid in different forms render different ids. GolemUI Forms sets it to the form's formName. Only ids and the references to them (for, aria-describedby…) take it: data-cy attributes and event details keep the bare uid. |
domId read-only, no attribute | string | – | The id of the element's control: uid, behind idPrefix when it is set. |
Form control properties
Every field has these, from the base class of the form controls.
| Property | Type | Default | Description |
|---|---|---|---|
name | string | – | The name the value is submitted under. Without it the element stays out of its form. Reflected, like a native control's: the form reads a single value's name from the attribute. |
label | string | – | The visible label, which also names the control for assistive technology. Without one the control has no accessible name; the date, time, range, tags and file fields warn about it in development builds. |
hint | string | – | Help text shown under the label and announced as the control's description. |
errors | string[] | [] | Error messages to show, typically from your own validation. They show as soon as they are set, unless touched is false. |
touched | boolean | – | Whether the user has interacted with the control. Leave it unset unless you validate on interaction: false holds errors back until it becomes true. |
required | boolean | false | The control needs a value: it is marked as required and, with a name, blocks submission. |
readOnly
attribute readonly | boolean | – | The value can be read and focused but not changed. |
disabled | boolean | – | Disabled by its own attribute or by a disabled <fieldset> around it. Setting the property sets the attribute, like a native control's. |
form read-only, no attribute | HTMLFormElement | null | – | The <form> the element belongs to, if any. |
validity read-only, no attribute | ValidityState | – | The element's validity, like a native control's. |
validationMessage read-only, no attribute | string | – | The message the browser shows for an invalid value. |
Methods
| Method | Description |
|---|---|
checkValidity(): boolean | – |
reportValidity(): boolean | – |
Events
Every event bubbles and is composed, so you can listen on any ancestor.
| Event | Description |
|---|---|
gui-input | The user picked or cleared a rating. detail.value is the new value. |
gui-change | The user committed the value. detail.value is the committed value. |
gui-blur | Focus left the stars. |
Examples
Section titled “Examples”Picking and clearing
Section titled “Picking and clearing”Until the user picks a star, or you set value, the rating has no value. A click on a star picks
it, and the stars up to it fill. The pointer previews the rating it would pick as it moves over
the stars.
A click on the picked star clears the rating, and so do Delete and Backspace. Try it on the rating at the top of the page.
Number of stars
Section titled “Number of stars”max sets how many stars there are, 5 by default. value is the number of stars picked, from 1
to max. As an attribute it is a number; from JavaScript, set the value property.
import { GuiRating } from '@golemui/gui-components/react';import '@golemui/gui-components/index.css';
export function RatingMax() { return ( <GuiRating label="How likely are you to recommend us?" max={10} value={7} /> );}import { Component, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';import '@golemui/gui-components/rating';
@Component({ selector: 'app-rating-max', schemas: [CUSTOM_ELEMENTS_SCHEMA], template: ` <gui-rating label="How likely are you to recommend us?" max="10" value="7" ></gui-rating> `,})export class RatingMaxComponent {}<script setup lang="ts">import '@golemui/gui-components/rating';import '@golemui/gui-components/index.css';</script>
<template> <gui-rating label="How likely are you to recommend us?" :max="10" :value="7" ></gui-rating></template>import { LitElement, html } from 'lit';import { customElement } from 'lit/decorators.js';import '@golemui/gui-components/rating';import '@golemui/gui-components/index.css';
@customElement('rating-max')export class RatingMax extends LitElement { protected override createRenderRoot() { return this; }
override render() { return html` <gui-rating label="How likely are you to recommend us?" max="10" value="7" ></gui-rating> `; }}<gui-rating label="How likely are you to recommend us?" max="10" value="7"></gui-rating>A value set from code that isn’t a whole number from 1 to max, such as 0, 7 of 5 or 3.5,
is kept. The element fills the stars it can, checks none, and reports the value as invalid, with
the rangeUnderflow, rangeOverflow or stepMismatch flag of its validity.
Disabled and read-only
Section titled “Disabled and read-only”A disabled rating can’t be focused or changed, and a form doesn’t submit it. A readonly
rating can be focused, but clicks and keys don’t change it, and a form submits its value. Use a
read-only rating to show a score, such as an average.
import { GuiRating } from '@golemui/gui-components/react';import '@golemui/gui-components/index.css';
export function RatingDisabledReadonly() { return ( <div className="gui-grid gui-grid--row"> <div className="gui-grid__cell"> <GuiRating label="Delivery" value={2} disabled /> </div> <div className="gui-grid__cell"> <GuiRating label="Average rating" value={4} readOnly /> </div> </div> );}import { Component, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';import '@golemui/gui-components/rating';
@Component({ selector: 'app-rating-disabled-readonly', schemas: [CUSTOM_ELEMENTS_SCHEMA], template: ` <div class="gui-grid gui-grid--row"> <div class="gui-grid__cell"> <gui-rating label="Delivery" value="2" disabled></gui-rating> </div> <div class="gui-grid__cell"> <gui-rating label="Average rating" value="4" readonly></gui-rating> </div> </div> `,})export class RatingDisabledReadonlyComponent {}<script setup lang="ts">import '@golemui/gui-components/rating';import '@golemui/gui-components/index.css';</script>
<template> <div class="gui-grid gui-grid--row"> <div class="gui-grid__cell"> <gui-rating label="Delivery" :value="2" :disabled="true"></gui-rating> </div> <div class="gui-grid__cell"> <gui-rating label="Average rating" :value="4" :readOnly="true" ></gui-rating> </div> </div></template>import { LitElement, html } from 'lit';import { customElement } from 'lit/decorators.js';import '@golemui/gui-components/rating';import '@golemui/gui-components/index.css';
@customElement('rating-disabled-readonly')export class RatingDisabledReadonly extends LitElement { protected override createRenderRoot() { return this; }
override render() { return html` <div class="gui-grid gui-grid--row"> <div class="gui-grid__cell"> <gui-rating label="Delivery" value="2" disabled></gui-rating> </div> <div class="gui-grid__cell"> <gui-rating label="Average rating" value="4" readonly></gui-rating> </div> </div> `; }}<div class="gui-grid gui-grid--row"> <div class="gui-grid__cell"> <gui-rating label="Delivery" value="2" disabled></gui-rating> </div> <div class="gui-grid__cell"> <gui-rating label="Average rating" value="4" readonly></gui-rating> </div></div>Errors
Section titled “Errors”errors takes a list of messages from your own validation, and shows them under the stars. Set
the errors property from a gui-change listener to validate as the user works. Clear the
rating below.
import { useState } from 'react';import { GuiRating } from '@golemui/gui-components/react';import '@golemui/gui-components/index.css';
export function RatingValidation() { const [value, setValue] = useState<number | undefined>(4); const errors = value ? [] : ['Rate the food to send your review.'];
return ( <GuiRating id="food" label="Food" value={value} errors={errors} onGuiChange={(event) => setValue(event.detail.value)} /> );}import { Component, CUSTOM_ELEMENTS_SCHEMA, signal } from '@angular/core';import type { GuiEventMap, GuiRatingEvents } from '@golemui/gui-components';import '@golemui/gui-components/rating';
type RatingEvent<K extends keyof typeof GuiRatingEvents> = GuiEventMap< typeof GuiRatingEvents>[K];
@Component({ selector: 'app-rating-validation', schemas: [CUSTOM_ELEMENTS_SCHEMA], template: ` <gui-rating id="food" label="Food" value="4" [errors]="errors()" (gui-change)="onChange($event)" ></gui-rating> `,})export class RatingValidationComponent { errors = signal<string[]>([]);
onChange(event: Event) { const { value } = (event as RatingEvent<'gui-change'>).detail; this.errors.set(value ? [] : ['Rate the food to send your review.']); }}<script setup lang="ts">import { ref } from 'vue';import '@golemui/gui-components/rating';import '@golemui/gui-components/index.css';
const errors = ref<string[]>([]);
function onChange(value: number | undefined) { errors.value = value ? [] : ['Rate the food to send your review.'];}</script>
<template> <gui-rating id="food" label="Food" :value="4" :errors.prop="errors" @gui-change="onChange($event.detail.value)" ></gui-rating></template>import { LitElement, html } from 'lit';import { customElement, state } from 'lit/decorators.js';import type { GuiEventMap, GuiRatingEvents } from '@golemui/gui-components';import '@golemui/gui-components/rating';import '@golemui/gui-components/index.css';
type RatingEvent<K extends keyof typeof GuiRatingEvents> = GuiEventMap< typeof GuiRatingEvents>[K];
@customElement('rating-validation')export class RatingValidation extends LitElement { @state() private errors: string[] = [];
protected override createRenderRoot() { return this; }
private onChange(event: RatingEvent<'gui-change'>) { this.errors = event.detail.value ? [] : ['Rate the food to send your review.']; }
override render() { return html` <gui-rating id="food" label="Food" value="4" .errors=${this.errors} @gui-change=${this.onChange} ></gui-rating> `; }}<gui-rating id="food" label="Food" value="4"></gui-rating>
<script type="module"> const food = document.querySelector('#food');
food.addEventListener('gui-change', (event) => { food.errors = event.detail.value ? [] : ['Rate the food to send your review.']; });</script>In a form
Section titled “In a form”With a name, <gui-rating> submits its value under that name, and nothing while it has none.
required blocks the submit until the user picks a star. The user can still clear a required
rating, as they can empty a required text field: it then blocks the submit again. Submit the form
below, then pick a star and submit again.
import { useState, type SubmitEvent } from 'react';import { GuiButton, GuiRating } from '@golemui/gui-components/react';import '@golemui/gui-components/index.css';
export function RatingNativeForm() { const [result, setResult] = useState('');
const onSubmit = (event: SubmitEvent<HTMLFormElement>) => { event.preventDefault(); const data = Object.fromEntries(new FormData(event.currentTarget)); setResult(`Submitted ${JSON.stringify(data)}`); };
return ( <form id="review" onSubmit={onSubmit}> <div className="gui-grid"> <div className="gui-grid__cell"> <GuiRating label="Your score" name="score" required /> </div> <div className="gui-grid__cell"> <GuiButton type="submit" label="Send review" /> </div> </div> <p id="review-result" role="status"> {result} </p> </form> );}import { Component, CUSTOM_ELEMENTS_SCHEMA, signal } from '@angular/core';import '@golemui/gui-components/button';import '@golemui/gui-components/rating';
@Component({ selector: 'app-rating-native-form', schemas: [CUSTOM_ELEMENTS_SCHEMA], template: ` <form id="review" #form (submit)="onSubmit($event, form)"> <div class="gui-grid"> <div class="gui-grid__cell"> <gui-rating label="Your score" name="score" required></gui-rating> </div> <div class="gui-grid__cell"> <gui-button type="submit" label="Send review"></gui-button> </div> </div> <p id="review-result" role="status">{{ result() }}</p> </form> `,})export class RatingNativeFormComponent { result = signal('');
onSubmit(event: SubmitEvent, form: HTMLFormElement) { event.preventDefault(); const data = Object.fromEntries(new FormData(form)); this.result.set(`Submitted ${JSON.stringify(data)}`); }}<script setup lang="ts">import { ref } from 'vue';import '@golemui/gui-components/button';import '@golemui/gui-components/rating';import '@golemui/gui-components/index.css';
const result = ref('');
function onSubmit(event: SubmitEvent) { if (!(event.currentTarget instanceof HTMLFormElement)) return; const data = Object.fromEntries(new FormData(event.currentTarget)); result.value = `Submitted ${JSON.stringify(data)}`;}</script>
<template> <form id="review" @submit.prevent="onSubmit"> <div class="gui-grid"> <div class="gui-grid__cell"> <gui-rating label="Your score" name="score" :required="true" ></gui-rating> </div> <div class="gui-grid__cell"> <gui-button type="submit" label="Send review"></gui-button> </div> </div> <p id="review-result" role="status">{{ result }}</p> </form></template>import { LitElement, html } from 'lit';import { customElement, query, state } from 'lit/decorators.js';import '@golemui/gui-components/button';import '@golemui/gui-components/rating';import '@golemui/gui-components/index.css';
@customElement('rating-native-form')export class RatingNativeForm extends LitElement { @query('#review') private form!: HTMLFormElement; @state() private result = '';
protected override createRenderRoot() { return this; }
private onSubmit(event: SubmitEvent) { event.preventDefault(); const data = Object.fromEntries(new FormData(this.form)); this.result = `Submitted ${JSON.stringify(data)}`; }
override render() { return html` <form id="review" @submit=${this.onSubmit}> <div class="gui-grid"> <div class="gui-grid__cell"> <gui-rating label="Your score" name="score" required></gui-rating> </div> <div class="gui-grid__cell"> <gui-button type="submit" label="Send review"></gui-button> </div> </div> <p id="review-result" role="status">${this.result}</p> </form> `; }}<form id="review"> <div class="gui-grid"> <div class="gui-grid__cell"> <gui-rating label="Your score" name="score" required></gui-rating> </div> <div class="gui-grid__cell"> <gui-button type="submit" label="Send review"></gui-button> </div> </div> <p id="review-result" role="status"></p></form>
<script type="module"> const form = document.querySelector('#review');
form.addEventListener('submit', (event) => { event.preventDefault(); const data = Object.fromEntries(new FormData(form)); document.querySelector('#review-result').textContent = `Submitted ${JSON.stringify(data)}`; });</script>The radio buttons inside stay out of the form: the element submits the value itself.
How the elements submit, validate and reset is in Native forms.
Styling
Section titled “Styling”Anatomy
Section titled “Anatomy”<gui-rating> renders into the light DOM, so you can style every part with plain CSS. These are
the parts and their public classes:
<gui-rating class="gui-field"> <span class="gui-label" id="service_label"> <span class="gui-label__text"> Service<span aria-hidden="true"> *</span> </span> <div class="gui-widget-hint" id="service_hint" aria-hidden="true"> How was your visit? </div> </span> <div class="gui-widget"> <div role="radiogroup" class="gui-rating__stars" id="service" aria-labelledby="service_label" aria-describedby="service_hint" aria-required="true" aria-invalid="true" aria-errormessage="service_errors" > <label class="gui-rating__star gui-rating__star--filled" for="service_1"> <input type="radio" class="gui-rating__input gui-visually-hidden" id="service_1" name="service" form="service_none" value="1" tabindex="-1" aria-label="1 star" aria-describedby="service_hint" aria-invalid="true" aria-errormessage="service_errors" aria-required="true" /> <svg viewBox="0 0 24 24" class="gui-rating__glyph" aria-hidden="true"> <polygon points="12,2 14.49,9.17 22.08,9.32 …"></polygon> </svg> </label> <!-- Stars 2 and 3, filled, the same way: the picked star takes Tab. --> <label class="gui-rating__star" for="service_4"> <input type="radio" class="gui-rating__input gui-visually-hidden" id="service_4" name="service" form="service_none" value="4" tabindex="-1" aria-label="4 stars" aria-describedby="service_hint" aria-invalid="true" aria-errormessage="service_errors" aria-required="true" /> <svg viewBox="0 0 24 24" class="gui-rating__glyph" aria-hidden="true"> <polygon points="12,2 14.49,9.17 22.08,9.32 …"></polygon> </svg> </label> <!-- One star per point up to max. --> </div> </div> <div class="gui-validator" id="service_errors" role="alert"> <div class="gui-validator__error">Rate the service.</div> </div></gui-rating>| Class | Part |
|---|---|
gui-field | The element itself. Lines its parts up with the fields next to it in a gui-grid row. |
gui-label | The label, with the text and the hint. |
gui-label__text | The label text and the required marker. |
gui-widget-hint | The hint. |
gui-widget | The box around the stars. |
gui-rating__stars | The stars, with the radiogroup role. |
gui-rating__stars--static | On the stars of a disabled or read-only rating: no pointer, and no preview on hover. |
gui-rating__star | One star: a <label> with its radio button and its glyph. |
gui-rating__star--filled | On each star up to the value. |
gui-rating__input | The radio button of a star, hidden on screen. |
gui-rating__glyph | The star’s drawing, an inline SVG. |
gui-validator | The errors container. It is always there, so the alert role announces new errors. |
gui-validator__error | One error message. |
An empty star is an outline and a filled one is solid, so the rating reads without telling
colors apart. In a right-to-left page the stars run from right to left. The ids derive from
uid, or from a generated id such as gui-rating-3 when you don’t set one. Select by class or by
tag, not by id.
Tokens
Section titled “Tokens”The rating reads these design tokens. Set them on :root to change every rating, or on any
element to change the ratings inside it:
| Token | What it styles |
|---|---|
--gui-rating-size | The width and height of each star. Defaults to 1.5rem. |
--gui-rating-gap | The space between the stars. Defaults to 0.125rem. |
--gui-rating-fill | The fill and outline of the filled stars, a warning shade by default. |
--gui-border-strong | The outline of the empty stars. |
--gui-radius-sm | The corners of a star’s focus ring. |
--gui-border-focus | The focus ring around the focused star. |
--gui-intent-error | The outline of the empty stars and the messages when there are errors. |
--gui-text-default | The label text. |
--gui-font-family | The font. |
--gui-font-sm | The text size of the label. |
--gui-font-xs | The text size of the hint and the errors. |
--gui-text-secondary | The hint. |
/* Bigger, red stars. */gui-rating { --gui-rating-size: 2rem; --gui-rating-fill: #d23c3c;}To restyle beyond the tokens, see Overriding styles; for dark mode and the Clay theme, see Themes and dark mode.
Accessibility
Section titled “Accessibility”- Group. The stars sit in an element with the
radiogrouprole, named by thelabelthrougharia-labelledby. Without a label the rating has no accessible name. Each star is a radio button named by its number, “1 star” to “5 stars”. The drawn stars are hidden from screen readers. - Description. The
hintis the rating’s description, througharia-describedby. - Errors. While errors show, the group and its radio buttons have
aria-invalid="true"and point at them witharia-errormessage, and screen readers announce new errors as they appear. - Required and read-only.
requiredsetsaria-required, andreadonlysetsaria-readonlyon the group, which radio buttons can’t carry themselves. - One tab stop. The rating is a single stop in the tab order: Tab lands on the
picked star, or on the first one when none is picked.
gui-blurfires only when focus leaves the stars: moving from one star to another doesn’t fire it. - Star names. The names come from the
ratingStarsmessage,{ one: '{count} star', other: '{count} stars' }. Translate it as explained in i18n.
| Key | Action |
|---|---|
| Tab | Moves focus to the picked star, or the first, and out. |
| ↓ → | Picks the next star, and fires gui-change. |
| ↑ ← | Picks the previous star, and fires gui-change. |
| Space | Picks the focused star. It never clears it. |
| Delete Backspace | Clears the rating, and fires gui-change. |
In a read-only rating these keys do nothing.
What every element shares, such as translating the browser messages, is in Accessibility.