日本語

How to Build a Star Rating Input in React

​​React​Accessibility,CSS,HTML,Playwright,TypeScript

You can build a star rating input by placing an <input type="radio"> for each star, hiding the radio button itself, and showing the "★" inside a label. Selecting with the arrow keys, sending the value with the form, and checking required are all handled by the browser, so on the React side you only need two state values: the number of the selected star and the number of the star under the mouse.

I built a StarRating component without using a library, and checked its behavior for mouse, keyboard, and form submission.

Note

The test environment was Ubuntu 24.04, Node.js 22.22.0, and Chromium 153. I used react / react-dom 19.3.1, @types/react 19.3.0, typescript 7.0.2, esbuild 0.28.2, and Playwright 1.63.0. I type-checked the .tsx with tsc, converted it with esbuild, and operated Chromium with Playwright. I did not test screen reader announcements, touch operation, Firefox, or Safari. For the information a screen reader would use, I checked by exporting the accessibility tree with Playwright.

Starting with nothing selected, moving the mouse from left to right over the stars lights them up in order. Clicking the fourth star shows "Selected value: 4", and pressing the left arrow key changes it to 3. (The label in the image is in Japanese.)
Three operations: hovering, clicking the fourth star, and pressing the ← key. The number for the selected value turns pink only at the moment it changes. (The pink number, cursor, click ring, key display, and operation counter were overlaid for the GIF. The labels in the image are in Japanese.)

Make each star a radio button

StarRating takes the name used when sending the form (name), the heading for the input (label), the number of stars (max), and other props. The whole component is wrapped in a fieldset, and the heading is written in a legend. Each star is wrapped in its own label, which contains a radio button and a "★".

tsx
import { useState } from 'react';

type Props = {
  name: string;
  label: string;
  max?: number;
  defaultValue?: number;
  required?: boolean;
  onChange?: (value: number) => void;
};

export function StarRating({ name, label, max = 5, defaultValue = 0, required, onChange }: Props) {
  const [value, setValue] = useState(defaultValue);
  // Number of the star under the mouse (0 when none)
  const [hover, setHover] = useState(0);
  const shown = hover || value;

  return (
    <fieldset className="star-rating" onMouseLeave={() => setHover(0)}>
      <legend>{label}</legend>
      {Array.from({ length: max }, (_, i) => {
        const n = i + 1;
        return (
          <label key={n} className={n <= shown ? 'star is-on' : 'star'} onMouseEnter={() => setHover(n)}>
            <input
              type="radio"
              className="visually-hidden"
              name={name}
              value={n}
              checked={value === n}
              required={required}
              onChange={() => {
                setValue(n);
                onChange?.(n);
              }}
            />
            <span aria-hidden="true">★</span>
            <span className="visually-hidden">星{n}つ</span>
          </label>
        );
      })}
    </fieldset>
  );
}

Radio buttons that share the same name form one group, and selecting one deselects the others. This behavior is described in MDN's guide to radio buttons. Because the star count works as a "pick one" input, React only needs to handle lighting up the stars up to the selected one.

Since checked is given a comparison with the state, this radio button is a "controlled component" whose value React manages. As described in React's official reference for input, when you pass checked, you also need to pass an onChange that updates the state.

The "★" characters have aria-hidden="true", so they are excluded from screen reader output. Instead, each radio button gets an accessible name such as "3 stars" from hidden text. When I exported the accessibility tree with Playwright, the group whose name is the Japanese label for "Rating for this article" contained five named radio buttons, as shown below.

text
- group "この記事の評価":
  - text: この記事の評価
  - radio "星1つ"
  - text: 星1つ
  - radio "星2つ"
  - text: 星2つ
  - radio "星3つ"
  - text: 星3つ
  - radio "星4つ"
  - text: 星4つ
  - radio "星5つ"
  - text: 星5つ

Do not hide radio buttons with display: none

The .visually-hidden class hides the radio button's circle by shrinking the element to 1px and clipping it. It disappears from the screen, but the element remains, so it can still receive focus and stays in the accessibility tree. Some lines of the styling (the margins for body and legend) are omitted.

css
.visually-hidden {
  position: absolute;
  width: 1px;
  height: 1px;
  margin: -1px;
  padding: 0;
  overflow: hidden;
  clip-path: inset(50%);
  white-space: nowrap;
  border: 0;
}

.star-rating {
  display: flex;
  gap: 4px;
  border: none;
  padding: 0;
  margin: 0;
}
.star {
  position: relative;
  font-size: 40px;
  line-height: 1;
  color: #c8d0d4;
  cursor: pointer;
}
.star.is-on {
  color: #f5b301;
}
.star:has(:focus-visible) {
  outline: 3px solid #067a98;
  outline-offset: 2px;
  border-radius: 4px;
}

For comparison, I also tested a version that hides the radio buttons with display: none. Clicking the fourth star set the value to 4, so mouse selection worked. However, the radio buttons disappeared from the accessibility tree, and the group contained only text. Pressing Tab skipped the stars and moved focus to the submit button.

text
- group "この記事の評価": この記事の評価 星1つ 星2つ 星3つ 星4つ 星5つ

MDN's explanation of display also says that elements with display: none are removed from the accessibility tree and are no longer read by screen readers.

Warning

With display: none, things work normally if you only test with a mouse, so it is easy to miss that the stars cannot be selected from the keyboard. When hiding radio buttons, keep the element and make it invisible, as in .visually-hidden above.

Change the star count only while the mouse is over the stars

The number of lit stars is determined by hover || value. This means the number of the star under the mouse if there is one, otherwise the selected value. The onMouseEnter on each label stores the number, and the onMouseLeave on the fieldset resets it to 0.

In my test environment, with nothing selected, hovering over the fourth star lit four stars, and moving the mouse away reset the count to 0. After clicking the third star, hovering over the fifth star lit five stars, and moving the mouse away returned the count to the selected 3. While hovering, the selected radio button remained 3. The results for each operation are summarized in the table below.

Operation Number of lit stars Selected star
Hover over the 4th star with nothing selected 4 None
Move the mouse out 0 None
Click the 3rd star 3 3rd
Hover over the 5th star 5 3rd
Move the mouse out 3 3rd
Click the 3rd star again 3 3rd

As the last row of the table shows, clicking the selected star again does not clear the selection. A radio button can only switch which option is chosen, not remove the selection. If you want to let users return to "no rating," you need a separate clear button (I did not build one in this article).

With the keyboard, the arrow keys change the star count

Since the radio buttons are used as they are, the browser handles keyboard operation. The table below shows the results in the test environment, pressing the keys from top to bottom starting from nothing selected.

Key pressed Where focus is Selected star
Tab 1st star None
→ 2nd star 2nd
→ 3rd star 3rd
Shift+Tab, then Tab 3rd star 3rd
← 2nd star 2nd
← twice (from the 1st star, one more to the left) 5th star 5th
→ (from the 5th star, one more to the right) 1st star 1st
Space 1st star 1st
Tab Submit button 1st

When nothing is selected and you enter with the Tab key, focus moves to the first star, but nothing is selected yet. Pressing the right arrow key here moves focus to the second star and selects it. To select the first star, press the Space key. After reloading the page and pressing Tab then Space from the unselected state, the first star was selected.

Pressing Space on a star that is already selected changed nothing (see the Space row in the table above). Once a star is selected, pressing Tab to return focuses the selected star. Since the group with five stars has only one Tab stop, you do not need to press Tab once for each star.

Pressing the left arrow key on the first star moved focus to the fifth star, and pressing the right arrow key on the fifth star moved focus to the first star. This may seem unusual for a rating input, but the radio group example in the W3C ARIA Authoring Practices Guide also moves from one end of the group to the other.

The focus ring is applied to the label with .star:has(:focus-visible). The radio button itself is invisible, so this draws the outline on the outer label when the inner radio button has focus. When operated with the keyboard, the outline appeared (outline was solid). When clicked with the mouse, it did not appear (none). As described in MDN's explanation of :focus-visible, this is because the browser decides when focus should be shown.

The value sent with the form, and what happens when it is required

When the component is placed inside a form, the value of the selected radio button is sent under its name. For testing, I prepared a screen that writes out the contents of FormData on submission.

tsx
import { useState, type FormEvent } from 'react';
import { StarRating } from './StarRating';

function App() {
  const [current, setCurrent] = useState(0);
  const [sent, setSent] = useState('');

  const handleSubmit = (e: FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    const data = new FormData(e.currentTarget);
    setSent(JSON.stringify(Object.fromEntries(data)));
  };

  return (
    <form onSubmit={handleSubmit}>
      <StarRating name="rating" label="この記事の評価" required onChange={setCurrent} />
      <p id="current">選んだ値:{current}</p>
      <button type="submit">送信</button>
      <p id="sent">{sent}</p>
    </form>
  );
}

When I selected the third star and submitted, {"rating":"3"} was sent. The value is the string "3", not a number, so convert it if you need a number.

I put required on all five radio buttons. According to MDN's explanation of radio buttons, if any radio button in a group with the same name has required, one of the buttons in that group must be selected. When I pressed submit without selecting anything, checkValidity() returned false, and the submit handler was not called (the written-out value stayed empty).

text
form.checkValidity(): false
validationMessage: Please select one of these options.
送信された値: ""

In the Chromium test environment, validationMessage was in English. Focus had moved to the radio button for the first star. According to the input validation section of MDN's explanation of radio buttons, when none of the buttons is selected, the browser asks the user to select one. You do not need to write your own code to check whether something is selected, because the browser handles it.

​Posted by 86