Clicked accordion not expanding when clicked with React's useState

Viewed 69

I have an accordion that works the way I need it to, except for one thing. After clicking on one of the accordion items, if another one that is collapsed is clicked, the one that was opened will close, but the one that was just clicked will not open.

Can anyone spot the problem in my code?

const [activeAccordion, setActiveAccordion] = useState(-1);

const handler = (index) => {
  setActiveAccordion(currentItem => currentItem === -1 ? index : -1);
};

// relevant section of code below...

{ items.map((e, c) => {
  return (
  <div key={`key${c}`}>
    <button className={styles.accordionButton} onClick={() => handler(c)}>
      {e.name}
    </button>
    {activeAccordion === c &&
      <div className={`${styles.accordionContent}`}>
1 Answers

You have a tiny problem in handler. Instead of setting the new item as a newly open one, you check currentItem === -1, and it will set activeAccordion back to -1 (which closes all accordions)

For the fix, you can change it to

const handler = (index) => {
  const isOpen = index === activeAccordion
  setActiveAccordion(isOpen ? -1 : index); //if it's open, we set -1 to close it
};
Related