Right now my all category getting clicked if I click on any single category. How I can prevent to show all category. see the screenshot
here I am clicking only electronic category but others category and sub category showing.
here is my code:
my list of data
const data =[
{
"id":1,
"main_category": "Electronic",
"sub_category": "mobile",
},
{
"id":2,
"main_category": "Pet",
"sub_category": "Home pet",
}
,
{
"id":3,
"main_category": "Furniture",
"sub_category": "kitchen",
}
]
my code start from here...
const PostAds = () => {
const[showsubcat,setShowSubCat] = useState(false)
let subcategory=(()=>{
setShowSubCat(prev=>!prev)
})
return (
<>{data.map((data)=>{
return(
<>
<li id="category" onClick={subcategory} >{data.main_category}</li>
{showsubcat &&
<li><i id="sub_category"></i> {data.sub_category}</li>
}
</>
CodePudding user response:
const[showsubcat,setShowSubCat] = useState(false)
This is setting a global state that is then re used on every category item that you have. Even though you have different <li>
tags they're all using the same showsubcat. I would recommend make a different component each li and then map that in your parent component.
const PostSingleAd = ({ data, itemOpenedId, setItemOpenedId }) => {
const [showsubcat, setShowSubCat] = useState(false);
let subcategory = () => {
setShowSubCat((prev) => !prev);
setItemOpenedId(data.id);
};
useEffect(() => {
if (itemOpenedId !== data.id) {
setShowSubCat(false);
}
}, [itemOpenedId]);
return (
<>
<li id="category" onClick={subcategory}>
{data.main_category}
</li>
{showsubcat && (
<li>
<i id="sub_category"></i>{" "}
{data.sub_category}
</li>
)}
</>
);
};
const PostAds = () => {
const [itemOpenedId, setItemOpenedId] = useState();
return data.map((data) => (
<PostSingleAd
data={data}
itemOpenedId={itemOpenedId}
setItemOpenedId={setItemOpenedId}
/>
));
};