Forms & Events — Intermediate React challenge.
Build a hoverable, accessible star rating component. Hovering previews a rating without committing it; clicking permanently selects a rating; the component is fully keyboard-operable and screen-reader friendly.
Requirements
- rating (selected) and hoverRating (temporary preview, null when not hovering) are tracked separately.
- While hovering, stars up to hoverRating show filled; while not hovering, stars up to the actual rating show filled.
- Clicking a star permanently sets rating; hovering afterward previews but always reverts to the selected rating on mouse leave, never to zero.
- Each star has role="radio", aria-checked, a descriptive aria-label (correct singular/plural wording), and is keyboard-operable via Enter or Space.
- Filled and empty stars use distinct CSS colors.
- A readout shows 'No rating yet' or 'X out of <maxStars>'.
Signature
function StarRating({
maxStars?: number;
onRatingChange?: (rating: number) => void;
}): JSX.ElementExample
<StarRating maxStars={5} />
// hover star 3 -> stars 1-3 preview as filled
// click star 4 -> rating locks to 4, "4 out of 5"
// hover star 5, then leave -> reverts to showing 4 filled, not 0Constraints
- Do not use a single boolean per star — derive filled/empty from rating and hoverRating.
- Every star must remain keyboard-accessible, not just clickable.