简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM