const [totalData, setTotalData] = useState([]);
const [dataList, setDataList] = useState([]);
const [selectedCategory, setSelectedCategory] = useState('');
filter를 할 대상을 상태에 담아놓고 UI에 그려지는 상태를 조작하여 랜더링이 이루어지게 작업을 한다. 카테고리별 필터링에서 이 부분이 헷갈렸다. 헷갈린 이유는 컴포넌트에서 props로 넘기는 과정에서 꼬이기 시작했다.
const handleCategory = categoryId => {
setSelectedCategory(categoryId);
setDataList(totalData.filter(el => el.category_id === categoryId));
};
위의 로직을 자식컴포넌트에서 만들려다 보니 props로 넘기는 양이 많아져 기능상의 문제가 생길 가능성이 높아보였다. 그리고 이부분에서 어느 것을 보내고 보내지 말아야 할 지 헷갈렸다.
자식컴포넌트에서 하던 로직을 부모로 옮겨서 함수를 만드니 만들어진 함수만 props로 보내주면 되서 작업이 엄청 수월해졌다.
const CategoryCard = ({ value, selectedCategory, handleCategory }) => {
return (
<StyledCategoryCard
onClick={() => {
handleCategory(value.category_id);
}}
>
<StyledCategoryImg alt="food" src={value.img} />
<StyledTitle isSelected={value.category_id === selectedCategory}>
{value.title}
</StyledTitle>
</StyledCategoryCard>
);
};