Currently, all accordion panels are being toggled simultaneously. I've tried passing in the index to the click handler, but no luck. How do I compare the current index with the current setActive variable to open and close accordion panels individually? The data I'm working with in production do not have unique ids which is why I'm using index. Thanks for any suggestions!
const Accordion = (props) => {
const [setActive, setActiveState] = useState(0);
const [setHeight, setHeightState] = useState("0px");
const [setRotate, setRotateState] = useState("accordion__icon");
const content = useRef(null);
const toggleAccordion = (index) => {
setActiveState(setActive === index ? "active" : "");
setHeightState(
setActive === "active" ? "0px" : `${content.current.scrollHeight}px`
);
setRotateState(
setActive === "active" ? "accordion__icon" : "accordion__icon rotate"
);
}
return (
<div>
{data.map((item, index) => (
<div key={index} className="accordion__section">
<button
className={`accordion ${setActive}`}
onClick={() => toggleAccordion(index)}
>
<p className="accordion__title">{item.title}</p>
<Chevron className={`${setRotate}`} width={10} fill={"#777"} />
</button>
<div
ref={content}
style={{ maxHeight: `${setHeight}` }}
className="accordion__content"
>
<div>{item.content}</div>
</div>
</div>
))}
</div>
);
};