Back to Dashboard
Machine CodingBASIC

Build an interactive Star Rating component with hover and click states.

ReactUIEvents

Live Interactive Demo

Loading Demo...

Implementation

typescript.tsx
import React, { useState } from 'react';
import { Star } from 'lucide-react';

const StarRating = ({ length = 5 }) => {
  const [selectedStar, setSelectedStar] = __PH_21__(0);
  const [hover, setHover] = __PH_22__(0);

  return (
    <div onMouseLeave={() => setHover(0)} className='flex gap-2 text-2xl font-bold font-mono'>
      {Array.__PH_15__({ length }).map((_, index) => {
        const starValue = index + 1;
        const isActive = hover >= starValue || (!hover && selectedStar >= starValue);
        return (
          <span
            key={index}
            className={isActive ? 'text-amber-400 scale-110' : 'text-slate-300 opacity-50'}
            onMouseEnter={() => setHover(starValue)}
            onClick={() => setSelectedStar(starValue)}
            style={{ cursor: 'pointer', transition: 'all 0.2s' }}
          >
            &#9733;
          </span>
        );
      })}
    </div>
  );
};

The Core Concept

A Star Rating component is a classic frontend task that tests state management and event handling. Key challenges include:

1. **Dual State Tracking**: You must track both the `actual rating` (selected) and the `hover rating` (temporary feedback). 2. **Conditional Styling**: Stars should be filled/colored based on whether their value is less than or equal to the current active rating (hover takes precedence over selected). 3. **Event Propagation**: Handling click events to set the rating while potentially allowing global reset logic. 4. **UX/Aesthetics**: Adding smooth transitions and visual feedback like glows or scales (Premium touch).