Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

210
Vistas
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 la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda