# Rating

`<wa-rating>`

Stable [Forms](https://webawesome.com/docs/components/?category=forms) [Since 2.0](https://webawesome.com/docs/resources/changelog#wa_200)

Ratings display a numeric score as a row of selectable symbols, typically stars. Use them to capture quick feedback or show an average rating for a product or piece of content.

```html
<wa-rating label="Rating"></wa-rating>
```

This component works with standard `<form>` elements. See [form controls](https://webawesome.com/docs/form-controls) for form submission and client-side validation.

## API

### Importing

If you're using the autoloader or a hosted project, components load on demand — no manual import needed. To cherry-pick a component manually, use one of the following snippets.

\*\*CDN\*\*

Import this component directly from the CDN:

```js
import 'https://ka-f.webawesome.com/webawesome@3.11.0/components/rating/rating.js';
```

\*\*npm\*\*

After installing Web Awesome via npm, import this component:

```js
import '@awesome.me/webawesome/dist/components/rating/rating.js';
```

\*\*Self-Hosted\*\*

If you're self-hosting Web Awesome, import this component from your server:

```js
import './webawesome/dist/components/rating/rating.js';
```

\*\*React\*\*

To import this component for React 18 or below, use the following code:

```js
import WaRating from '@awesome.me/webawesome/dist/react/rating/index.js';
```

### Attributes & Properties

| Name | Description | Reflects |
| --- | --- | --- |
| \`defaultValue\` default-value | \`number\` The default value of the form control. Used to reset the rating to its initial value. Type Default 0 | |
| \`disabled\` disabled | \`boolean\` Disables the rating. Type Default false | |
| \`form\` | \`

\` By default, form controls are associated with the nearest containing element. This attribute allows you to place the form control outside of a form and associate it with the form that has this id. The form must be in the same document or shadow root for this to work. Type HTMLFormElement \\| null | |
| \`getSymbol\` getSymbol | \`\` A function that customizes the symbol to be rendered. The first and only argument is the rating's current value. The function should return a string containing trusted HTML of the symbol to render at the specified value. Works well with elements. Type (value: number, isSelected: boolean) => string | |
| \`label\` label | \`string\` A label that describes the rating to assistive devices. Type Default '' | |
| \`max\` max | \`number\` The highest rating to show. Type Default 5 | |
| \`name\` name | \`string \\| null\` The name of the rating, submitted as a name/value pair with form data. Type Default null | |
| \`precision\` precision | \`0.5\` The precision at which the rating will increase and decrease. For example, to allow half-star ratings, set this attribute to . Type number Default 1 | |
| \`readonly\` readonly | \`boolean\` Makes the rating readonly. Type Default false | |
| \`required\` required | \`boolean\` Makes the rating a required field. Type Default false | |
| \`size\` size | \`'xs' \\| 's' \\| 'm' \\| 'l' \\| 'xl' \\| 'small' \\| 'medium' \\| 'large'\` The component's size. Type Default 'm' | |
| \`validationTarget\` | \`undefined \\| HTMLElement\` Override this to change where constraint validation popups are anchored. Type | |
| \`validators\` | \`observedAttributes\` Validators are static because they have , essentially attributes to "watch" for changes. Whenever these attributes change, we want to be notified and update the validator. Type Validator\[\] Default \[\] | |
| \`value\` value | \`number\` The current rating. Type Default 0 | |

### Methods

| Name | Description | Arguments |
| --- | --- | --- |
| \`formStateRestoreCallback()\` | Called when the browser is trying to restore element’s state to state in which case reason is "restore", or when the browser is trying to fulfill autofill on behalf of user in which case reason is "autocomplete". In the case of "restore", state is a string, File, or FormData object previously set as the second argument to setFormValue. | \`state: string \\| File \\| FormData \\| null, reason: 'autocomplete' \\| 'restore'\` |
| \`resetValidity()\` | Reset validity is a way of removing manual custom errors and native validation. | |
| \`setCustomValidity()\` | Do not use this when creating a "Validator". This is intended for end users of components. We track manually defined custom errors so we don't clear them on accident in our validators. | \`message: string\` |

### Events

| Name | Description |
| --- | --- |
| \`change\` | Emitted when the rating's value changes. |
| \`wa-hover\` | \`phase\` Emitted when the user hovers over a value. The property indicates when hovering starts, moves to a new value, or ends. The value property tells what the rating's value would be if the user were to commit to the hovered value. |
| \`wa-invalid\` | Emitted when the form control has been checked for validity and its constraints aren't satisfied. |

### CSS Custom Properties

| Name | Description |
| --- | --- |
| \`--symbol-color\` | The inactive color for symbols. |
| \`--symbol-color-active\` | The active color for symbols. |
| \`--symbol-spacing\` | The spacing to use around symbols. |

### CSS Parts

| Name | Description | CSS selector |
| --- | --- | --- |
| \`rating\` | The component's outer wrapper. | \`::part(rating)\` |
| \`base\` | \`rating\` Deprecated. Use the part instead. | \`::part(base)\` |

### Dependencies

This component automatically imports the following elements. Sub-dependencies, if any exist, will also be included in this list.

-   [`<wa-icon>`](https://webawesome.com/docs/components/icon)

## Examples

### Label

Ratings are usually identified by context, so the label isn't displayed. Always provide one with the `label` attribute so assistive devices can announce the control.

```html
<wa-rating label="Rate this component"></wa-rating>
```

### Disabled

Use the `disabled` attribute to disable the rating.

```html
<wa-rating label="Rating" disabled value="3"></wa-rating>
```

### Readonly

Use the `readonly` attribute to display a rating that users can't change. Unlike `disabled`, a readonly rating still submits its value with the form.

```html
<wa-rating label="Rating" readonly value="3"></wa-rating>
```

### Size

Use the `size` attribute to change the rating's size.

```html
<div class="wa-stack">
  <wa-rating label="Extra small" size="xs"></wa-rating>
  <wa-rating label="Small" size="s"></wa-rating>
  <wa-rating label="Medium" size="m"></wa-rating>
  <wa-rating label="Large" size="l"></wa-rating>
  <wa-rating label="Extra large" size="xl"></wa-rating>
</div>
```

For finer control, set the `font-size` property directly.

```html
<wa-rating label="Rating" style="font-size: 3rem;"></wa-rating>
```

### Max Value

Ratings go from 0 to 5 by default. Use the `max` attribute to change the highest possible value.

```html
<wa-rating label="Rating" max="3"></wa-rating>
```

### Precision

Use the `precision` attribute to let users select fractional ratings, such as half stars.

```html
<wa-rating label="Rating" precision="0.5" value="2.5"></wa-rating>
```

### Custom Icons

Pass a function to the `getSymbol` property to render a custom symbol in place of the default star.

```html
<wa-rating label="Rating" class="rating-hearts" style="--symbol-color-active: #ff4136;"></wa-rating>

<script type="module">
  const rating = document.querySelector('.rating-hearts');

  await customElements.whenDefined('wa-rating');
  await rating.updateComplete;

  rating.getSymbol = () => '<wa-icon name="heart" variant="solid"></wa-icon>';
</script>
```

### Value-Based Icons

The `getSymbol` function receives the symbol's value and whether it's currently selected, so you can render different icons across the scale.

```html
<wa-rating label="Rating" class="rating-emojis"></wa-rating>

<script type="module">
  const rating = document.querySelector('.rating-emojis');

  await customElements.whenDefined('wa-rating');
  await rating.updateComplete;

  rating.getSymbol = (value, isSelected) => {
    const icons = ['face-angry', 'face-frown', 'face-meh', 'face-smile', 'face-laugh'];
    return `<wa-icon name="${icons[value - 1]}"></wa-icon>`;
  };
</script>
```

### Detecting Hover

Use the `wa-hover` event to react as the user hovers over (or touches and drags across) the rating, before they commit to a value.

The event's `detail` carries `phase` and `value`. The `phase` property reports when hovering starts, moves to a new value, and ends. The `value` property is what the rating would become if the user committed to the hovered symbol.

```html
<div class="detect-hover">
  <wa-rating label="Rating"></wa-rating>
  <span></span>
</div>

<script>
  const rating = document.querySelector('.detect-hover > wa-rating');
  const span = rating.nextElementSibling;
  const terms = ['No rating', 'Terrible', 'Bad', 'OK', 'Good', 'Excellent'];

  rating.addEventListener('wa-hover', event => {
    span.textContent = terms[event.detail.value];

    // Clear feedback when hovering stops
    if (event.detail.phase === 'end') {
      span.textContent = '';
    }
  });
</script>

<style>
  .detect-hover span {
    position: relative;
    top: -4px;
    left: 8px;
    border-radius: var(--wa-border-radius-m);
    background: var(--wa-color-neutral-fill-loud);
    color: var(--wa-color-neutral-on-loud);
    text-align: center;
    padding: 4px 6px;
  }

  .detect-hover span:empty {
    display: none;
  }
</style>
```

### Required

Use the `required` attribute to make the rating mandatory. The form won't submit until the user selects a value.

```html
<form class="rating-required">
  <wa-rating label="Rating" required></wa-rating>
  <br /><br />
  <wa-button appearance="filled" type="submit">Submit</wa-button>
</form>

<script type="module">
  const form = document.querySelector('.rating-required');

  await Promise.all([customElements.whenDefined('wa-button'), customElements.whenDefined('wa-rating')]).then(() => {
    form.addEventListener('submit', event => {
      event.preventDefault();
      alert('All fields are valid!');
    });
  });
</script>
```

### Custom Validity

Use the `setCustomValidity()` method to set a custom validation message. This prevents the form from submitting and makes the browser display your message. Pass an empty string to clear the error.

```html
<form class="rating-custom-validity">
  <wa-rating label="Rating"></wa-rating>
  <br /><br />
  <wa-button appearance="filled" type="submit">Submit</wa-button>
</form>

<script type="module">
  const form = document.querySelector('.rating-custom-validity');
  const rating = form.querySelector('wa-rating');
  const errorMessage = 'Please rate at least 3 stars!';

  customElements.whenDefined('wa-rating').then(async () => {
    await rating.updateComplete;
    rating.setCustomValidity(errorMessage);
  });

  rating.addEventListener('change', () => {
    rating.setCustomValidity(rating.value >= 3 ? '' : errorMessage);
  });

  await Promise.all([customElements.whenDefined('wa-button'), customElements.whenDefined('wa-rating')]).then(() => {
    form.addEventListener('submit', event => {
      event.preventDefault();
      alert('All fields are valid!');
    });
  });
</script>
```

### Form Submission

Ratings work in forms just like native form controls. The rating's `name` and `value` are included in the form data on submit.

```html
<form class="rating-form-submission" action="about:blank" method="get" target="_blank">
  <wa-rating name="rating" label="How would you rate your experience?" required></wa-rating>
  <br /><br />
  <wa-button type="submit">Submit</wa-button>
  <wa-button appearance="filled" type="reset" variant="neutral">Reset</wa-button>
</form>
```
