sorry to ask. I have a button, then I add an active class when I click it, but when I click it all the buttons become active, how do I fix it? this is the code
<div className="">
{category.items.length === 0 ? (
<div>There is no property at this categories</div>
) : (
category.items.map((item, index2) => {
return (
<div key={`category-${index1}-item-${index2}`}>
{buttons.map((buttonLabel, i) => (
<button
key={i}
name={buttonLabel}
onClick={(event) => handleClick(event, i)}
className={
i === clickedId
? 'py-4 pl-3 customButton active '
: 'customButton py-4 pl-3'
}
>
{item.name}
</button>
))}
</div>
);
})
)}
</div>
and this is code when button called
<ButtonCategory
data={category.categories}
buttons={[category.categories]}
doSomethingAfterClick={printButtonLabel}
/>
you are returning the same set of buttons for each item. there are better ways to do this but with you current setup this should work:
buttons.map((buttonLabel, i) => {
const key = `${index2}.${i}`
return (
<button
key={key}
name={buttonLabel}
onClick={(event) => handleClick(event, key)}
className={
key === clickedId
? "py-4 pl-3 customButton active "
: "customButton py-4 pl-3"
}
>
{item.name}
</button>
)});
just don't forget to initialize your clickedId state as null or undefned instead of number
youd should set index of the clicked button as clickedId in handleClick function. so your handleClick function must be like this
const handleClick = (event, i) => {
setClickedId(i)
// other logic
}