import React, { useEffect, useState } from "react"; import { FaStar } from "react-icons/fa"; interface Star { id: number; hover: boolean; active: boolean; } const defaultStars: Star[] = [ { id: 1, hover: false, active: true }, { id: 2, hover: false, active: true }, { id: 3, hover: false, active: true }, { id: 4, hover: false, active: false }, { id: 5, hover: false, active: false }, ]; interface RatingProps { onChange?: (value: number, name: string) => void; name?: string; } const Rating: React.FC = ({ onChange = () => {}, name = "" }) => { const [stars, setStars] = useState(defaultStars); const [rating, setRating] = useState(3); const onMouseEnter = (star: Star) => { const index = stars.indexOf(star); const modifiedStars = stars.map((s, i) => ({ ...s, hover: i <= index })); setStars(modifiedStars); }; const onMouseLeave = () => { setStars((prev) => prev.map((s) => ({ ...s, hover: false }))); }; const onClick = (star: Star) => { const index = stars.indexOf(star); setRating(index + 1); onChange(index + 1, name); const modifiedStars = stars.map((s, i) => ({ ...s, active: i <= index })); setStars(modifiedStars); }; console.log("stars2", stars); console.log("rating2", rating); useEffect(() => { setStars(defaultStars); }, []); return (
{stars.map((star) => ( onMouseEnter(star)} onClick={() => onClick(star)} > ))}
); }; export default Rating;