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

209
Visualizações
React collapsing div animation with CSS

I don't really understand why my component doesn't work. I want to create a component which expand/collapse when you click the button. It works fine, but I have a problem with the animation. When I click the button, website crashes. This is my component:

import { useState, useRef, React } from 'react'

const Collapsible = ({ desc, text }) => {
    const [isOpen, setIsOpen] = useState(false);
    const parentRef = useRef();

  return (
    <div className='city'>
        <button className='toggle-btn' onClick={()=> {
            setIsOpen(!isOpen);
        }}>{text}</button>
        
        { isOpen && 
        <div 
        className="city-info" 
        ref={parentRef}
        style={isOpen ? {
            height: parentRef.current.scrollHeight + "px",
        }:{
            height: "0px",
        }}
        >{desc}</div>}
    </div>
  )
}

export default Collapsible

And this is the error I get:

Uncaught TypeError: Cannot read properties of undefined (reading 'scrollHeight')

Why is it undefined? After a long time of trying to do it by myself, I gave up and I did a step-by-step with tutorial and it works great in the tutorial.

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