Overview
Imagine you're enhancing the product review section for 'StellarMart', a popular online electronics store. Your task is to build a reusable Star Rating widget that allows users to visually select a rating. This problem focuses on core React component development, state management, and user interaction for a common UI pattern.
What you need to do / Task
- Create a
StarRating React component.
- Display a configurable number of star icons (e.g., 5 stars).
- Allow users to hover over stars to preview a rating.
- Allow users to click a star to select a permanent rating.
- Visually indicate the current selected rating and the hover-preview rating.
- Implement accessibility considerations for keyboard navigation and screen readers.
UI/UX expectations
- Layout: Stars should appear in a horizontal row, evenly spaced.
- Visual State:
- Unrated stars: Empty/outline icon (e.g.,
☆).
- Rated stars: Filled icon (e.g.,
★) up to the selected rating.
- Hovered stars: Filled icon up to the hovered star, overriding the selected rating visually until hover ends.
- Interaction:
- Hovering a star should fill it and all preceding stars.
- Clicking a star should set the permanent rating to that star's value.
- Moving the mouse off the component should revert the visual state to the selected permanent rating.
- Keyboard interaction: Users should be able to navigate stars with arrow keys (left/right) and select with Space or Enter.
- Cursor: Pointer cursor on hover over stars.
Acceptance criteria
- The component renders
N star icons based on a maxStars prop.
- Initially, stars reflect the
initialRating prop.
- Hovering over the 3rd star fills stars 1, 2, and 3.
- Clicking the 4th star sets the permanent rating to 4, visually filling stars 1-4.
- Hovering off the component resets the visual state to the permanent rating.
- The
onRatingChange callback is invoked with the new rating when a star is clicked.
- Component is accessible: keyboard navigation (arrow keys, Space/Enter) and appropriate
aria-label or aria-valuetext attributes for screen readers.
Clarifications
- Q: Can I use an icon library? A: No, use simple characters (e.g., '★' / '☆') or SVG elements directly.
- Q: How should
onRatingChange behave? A: It should be called only on click, not on hover.
- Q: What if the user clicks the same rating again? A: The rating should remain the same; clicking an already selected star should not un-rate it.