Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

108
Views
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}`}>
about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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
};
about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!