Loading workspace…

Star Rating

Yangshun TayEx-Meta Staff Engineer
Languages

Create a star rating widget that allows users to select a rating value.

Requirements

  • The widget accepts three parameters: the maximum number of stars, the number of currently filled stars, and a callback fired with the new value whenever the rating changes.
  • When a star is clicked, it is filled along with all the stars to its left, and the change callback is fired with the new rating.
    • The widget may start with zero filled stars. Clicking a star selects a rating from 1 to the maximum; clicking the selected star again keeps that rating. Clearing the rating back to zero is not required.
  • Hovering over a star fills that star and all stars to its left.
    • The stars that need to be filled during hover take priority over the existing filled state.
    • If the cursor leaves the widget and no new selection is made, the appropriate stars revert to the filled state before hovering.
  • Make the star rating widget reusable such that multiple instances can be rendered within the same page.

The star icons, both empty and filled, are provided as SVGs.

Changelog

  1. Zero ratings and hover preview

    The prompt specifies that zero is allowed initially and clicking the selected star keeps its rating. The Svelte solution also updates the filled stars when the selection or hover preview changes.

  2. Keyboard rating controls

    The React, Vue, Angular, and Vanilla JavaScript solutions use buttons for the stars so a focused star can be selected from the keyboard. The Vanilla JavaScript example also demonstrates the rating callback.

  3. Rating change callback

    The widget takes a callback in addition to the maximum and current rating. It reports the new rating when the user changes it.

A star-rating.tsx skeleton component has been created for you. You are free to decide the props of <StarRating />.