Sequence NODE_197
Medium

Create a Star Rating Component

React
JavaScript
Technical Specification

Build a 1–5 star rating component that allows user to select a rating.

Input/Output Samples
Input:Click 4th star
Output:Rating set to 4
Optimal Logic Path
import { useState } from "react";

function StarRating() {
  const [rating, setRating] = useState(0);
  const [hover, setHover] = useState(0);

  return (
    <div>
      {Array.from({ length: 5 }, (_, i) => {
        const value = i + 1;
        const active = value <= (hover || rating);
        return (
          <span
            key={value}
            onClick={() => setRating(value)}
            onMouseEnter={() => setHover(value)}
            onMouseLeave={() => setHover(0)}
            style={{ cursor: "pointer", color: active ? "gold" : "gray" }}
          >
            ★
          </span>
        );
      })}
    </div>
  );
}
Architectural Deep-Dive
We highlight stars based on hover first, otherwise the saved rating.