import React, { useState } from 'react';
import { FaStar } from 'react-icons/fa';
const createArr = (length: number): unknown[] => [...Array(length)];
const Star = ({ selected = false, onSelected }: { selected: boolean; onSelected: () => void }) => {
return (
<>
<FaStar color={selected ? 'yellow' : 'grey'} onClick={onSelected} />
</>
);
};
export default function StarGrade({ totalStar = 5 }: { totalStar?: number }) {
const [selectedStar, setSelectedStar] = useState(0);
return (
<>
{createArr(totalStar).map((item, idx) => (
<Star key={idx} selected={selectedStar > idx} onSelected={() => setSelectedStar(idx + 1)} />
))}
<p>
{selectedStar} / {totalStar}
</p>
</>
);
}
Star 컴포넌트의 재사용성을 생각한 별점 컴포넌트를 작성해 보았습니다.
만약, 재사용성을 배제하고 캡슐화를 원한다면 외부 Star 컴포넌트를 뺴고 반환하는 FaStar 컴포넌트를 안으로 집어 넣으면 될 것같습니다.
import React, { useState } from 'react';
import StarGrade from './components/StarGrade';
export default function Home() {
return (
<>
<div>
<StarGrade/>
</div>
</>
)
}