Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Clicked accordion not expanding when clicked with React's useState

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}`}>

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading