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

134
Views
Keep the first accordion item opened

I have a React Js accordion, when i click an item, the panel opens, to close it you have to click the same item or another item, i need the keep the first item opened in the beginning.

The method eventHandler gets the id of each item of the accordion, these items are fetched from an API, everytime i click an item i get the id of the item, but when the component mounts the console.log(active) returns null

I need to get the id of the first item, because the first index is not gonna be 0 so useState(0) won't help, any ideas how to do so?

Here is my code :

const { active, setActive } = useContext(AccordionContext)

const eventHandler = (e, index) => {
    e.preventDefault();
    setActive(index !== active ? index : null);
}

return (
    <div id={props.index}>
        <button
            onClick={(e) => eventHandler(e, props.index)}
            aria-expanded={ active === props.index ? 'true' : 'false' }
            aria-disabled={ active === props.index ? 'true' : 'false' }
        >
            <span>
                {props.description}
            </span>
        </button>
        <div>
            <div toggle={active === props.index}></div>
        </div>
    </div>
)

And here is the AccordionContext

const AccordionWrapper = (props) => {

    const [active, setActive] = useState(null);

    console.log(active)

    return (
        <AccordionContext.Provider
            value={{
                active, setActive
            }}
        >
            <AccWrapper>
                {props.children}
            </AccWrapper>
        </AccordionContext.Provider>
    )
}
about 4 years ago · Juan Pablo Isaza
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!