• Empleos
  • Sobre nosotros
  • profesionales
    • Inicio
    • Empleos
    • Cursos y retos
    • Preguntas
    • Profesores
  • empresas
    • Inicio
    • Publicar vacante
    • Nuestro proceso
    • Precios
    • Pruebas Online
    • Nómina
    • Blog
    • Comercial
    • Calculadora de salario

0

189
Vistas
element.current.scrollHeight not returning real height (React, CSS)

I have a <div> container that will be populated with some tags as the user selects options on a dropdown. If the tags fill the space I designated for the container, I want to display a "+N" tag with the remaining number of selected options.

Expected output: the isOverflowing condition sets to true.

Actual output: isOverflowing is never set to true.

CODE

const [selectedOptions, setSelectedOptions] = useState<number[]>([]);
const [overflowing, setOverflowing] = useState(false);

const tagsRef = useRef<HTMLDivElement>(null);

const isOverflowing = (element: any) => {
  return element.current?.scrollHeight > element.current?.clientHeight; // NEVER RETURNS TRUE
};

useLayoutEffect(() => {
  if (isOverflowing(tagsRef)) {
    setOverflowing(true);
  } else {
    setOverflowing(false);
  }
}, [tagsRef, selectedOptions]);

...

return (
  <TagsWrapper ref={tagsRef} className="tagsWrapper">
    {selectedOptions.map((option, index) => (
      ...
    ))}
  </TagsWrapper>
)

CSS

.tagsWrapper {
  display: flex;
  flex-flow: row wrap;
  max-height: 32px;
  max-width: calc(100% - 50px - 16px - 4px);
  overflow: hidden;
}

Console logging the tagsRef always shows that scrollHeight and clientHeight are the same, when in fact they are not (I can see that the div is taller when I inspect it on the browser).

I've tried many combinations of max-height, height... to no avail. If the overflow property is set to visible it works, obviously, but I don't want to show the remaining tags... Is there a solution I'm not seeing?

Thanks!

almost 3 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

I managed to see my own problem. The max-height and overflow properties should be on the parent element of overflowing container:

<TagsContainer>
  <TagsWrapper ref={tagsRef} className="tagsWrapper">
    {selectedOptions.map((option, index) => (
      ...
    ))}
  </TagsWrapper>
</TagsContainer>
.tagsContainer {
  max-height: 32px;
  overflow: hidden;
}
.tagsWrapper {
  display: flex;
  flex-flow: row wrap;
  ...
}
almost 3 years ago · Juan Pablo Isaza Denunciar
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 Nuestro proceso Comercial
Legal
Términos y condiciones Política de privacidad
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recomiéndame algunas ofertas
Necesito ayuda