Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

140
Visualizações
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
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda