Star RatingLoading saved progress…

Star Rating

Build the classic five-star rating control as a single React component. The twist that makes it feel real is the hover preview: as the pointer moves across the stars, the fill follows it — and each star splits in half, so hovering the left edge of the third star previews 2.5. Clicking commits that value; moving away shows what you committed.

Task

The starter App.tsx renders five empty stars and "No rating". Make it interactive:

  1. Two pieces of state. Track a committed rating and a transient hover, both useState(0). The display value is hover || rating — hover wins while the pointer is over the row, otherwise you see the committed rating.
  2. Half-star hover. onMouseMove over a star reads the cursor's offsetX: the left half previews i + 0.5, the right half i + 1. Store that in hover.
  3. Commit and reset. onClick sets rating to the hovered value; onMouseLeave on the row sets hover back to 0.
  4. Render the fill. Fill each star to Math.max(0, Math.min(1, value - i)) * 100 percent, and show 3.5 / 5 (or "No rating" when the value is 0) in the label.

Examples

  • Hover the left half of the 3rd star: the first two fill fully, the third fills halfway, and the label reads "2.5 / 5".
  • Click there: the rating commits to 2.5. Move the mouse off the row and the same 2.5 stays shown.
  • Move back and hover the 5th star's right half: the preview jumps to "5 / 5" — until you leave, when it snaps back to the committed 2.5.

Notes

  • Display value = hover || rating. One derived value drives both the fill and the label. Since a real rating is never 0 once set, hover || rating is a clean "preview beats committed" rule.
  • Half comes from offsetX. Compare the cursor's offsetX to the star's offsetWidth; under half is .5, over half is a whole star.
  • The fill is one clipped overlay. A gold is layered over a grey and clipped with width50% shows a half star. No separate half-star glyph needed.
  • Styling (dark theme, star sizing, gold fill) is already in styles.css; focus on the state and the offset math.
Loading editor…
Loading preview…