Star Rating
Build an interactive five-star rating control. Clicking the Nth star sets the rating to N, and a live status region reports the current rating out of 5.
Create a StarRating widget using React state.
Render five star buttons in a row. Each button is accessible and labeled "Rate 1 star", "Rate 2 stars", "Rate 3 stars", "Rate 4 stars", and "Rate 5 stars" respectively (note the singular "star" only for the first, plural "stars" for the rest).
Clicking the Nth star sets the current rating to N. A role="status" element displays the current rating as "{rating} of 5". Before any star is clicked, the rating is 0, so the status reads "0 of 5".
Rating is sticky: clicking star 3, then star 5, then star 2 leaves the rating at 2 — it always reflects the most recently clicked star. Visually, stars at or below the current rating should look "filled" (e.g. ★) and the rest "empty" (e.g. ☆), but the tests only assert on the status text and the button labels, so the exact glyphs are up to you.
Requirements
- Render exactly five star buttons, each a real <button> element.
- Each star button has an aria-label: 'Rate 1 star', 'Rate 2 stars', 'Rate 3 stars', 'Rate 4 stars', 'Rate 5 stars'.
- Track the current rating in React state (useState), starting at 0.
- Clicking the Nth star sets the rating to N.
- A role="status" element shows the text '{rating} of 5', initially '0 of 5'.
- Re-clicking a different star updates the rating to that star's value (most recent click wins).
Hints (4)
- Build the five buttons from an array like [1,2,3,4,5].map(...) so the label and click handler are derived from the star number.
- The label is singular only for star 1: use
Rate ${n} star${n === 1 ? '' : 's'}. - Keep the rating in useState initialized to 0, and set it to the clicked star's number in onClick.
- Render the status text as
${rating} of 5inside an element with role="status" so screen readers and tests can read the live value.
Topics
- React
- React Components
Asked at
Uber · Delhivery · PhonePe · Freshworks · Myntra · Flipkart
