filter와 find 메서드를 사용해서 버튼을 중복 선택하기
const DateFilterData = [
{
id: 1,
value: "전체",
},
{
id: 2,
value: "쇼핑몰",
},
{
id: 3,
value: "마켓",
},
{
id: 4,
value: "로드샵",
},
{
id: 5,
value: "디자이너브랜드",
},
{
id: 6,
value: "제너럴브랜드",
},
{
id: 7,
value: "내셔널브랜드",
},
{
id: 8,
value: "뷰티",
},
];
export default DateFilterData;
import React, { useState, useEffect } from "react";
import SellerAttriFilterData from "../../Data/SellerAttriFilterData";
function FilterArea() {
const [duplicated, setDuplicated] = useState(["전체"]);
useEffect(() => {
if (duplicated.length === 7 || duplicated.length === 0) {
setDuplicated(["전체"]);
}
}, [duplicated]);
const handleDuplicated = (e) => {
console.log(e.target.value);
const isIncludes = duplicated.find((el) => el === e.target.value);
if (e.target.value === "전체") {
setDuplicated(["전체"])
}
else if (isIncludes) {
setDuplicated(duplicated.filter((el) => el !== e.target.value));
}
else if (duplicated.length > 0) {
setDuplicated([...duplicated.filter((el) => el !== "전체"), e.target.value,
]);
}
return(
<SellerAttri>
<SellerAttriBtn>
{SellerAttriFilterData.map((el, index) => (
<AttriBtn
key={index}
type="button"
onClick={handleDuplicated}
value={el.value}
backgroundColor={duplicated.find(
(element) => element === el.value
)}
>
{el.value}
</AttriBtn>
))}
</SellerAttriBtn>
</SellerAttri>
);
}
export default FilterArea;
const AttriBtn = styled.button`
margin: 0 3px;
padding: 6px 12px;
font-size: 14px;
font-weight: 400;
// props로 넘겨준 스타일은 backgroundColor의 조건이 만족될 시에만, 실행이 된다.
color: ${({ backgroundColor }) => (backgroundColor ? "white" : "black")};
background-color: ${({ backgroundColor }) =>
backgroundColor ? "#428bca" : "#fff"};
border: 1px solid #e5e5e5;
border-radius: 4px;
outline: none;
cursor: pointer;
&:hover {
color: #333;
color: ${({ backgroundColor }) => (backgroundColor ? "white" : "black")};
background-color: ${({ backgroundColor }) =>
backgroundColor ? "#428bca" : "#e6e6e6"};
border-color: #adadad;
}
`;