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

157
Vistas
Dynamically adding items to an array

I'm having trouble adding items to the array. I want to get the heights of <p> elements on the page and add them to the array. But every time it gets an array with one element, it looks like the previous value is resetting.

const Paragraph = () => {
  const [height, setHeight] = useState(0);
  const [arrayWithHeight, setArrayWithHeight] = useState([]);

  const ref = useRef(null);

  useEffect(() => {
    setHeight(ref.current.clientHeight);
    addItemsToArray(ref.current.clientHeight);
  }, [addItemsToArray]);



  function addItemsToArray(height) {
    setArrayWithHeight(heights => [...heights, height]);
  }

  console.log('arrayWithHeight', arrayWithHeight)

  return (
   <div>
      <p ref={ref}>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum</p>
      <p ref={ref}>Lorem ipsum dolor sit amet</p>
      <p ref={ref}>Lorem</p>
    </div>

  );
};

export default Paragraph; Examples of output: [113], [124], [55]. However, I would like to receive one table [113,124,55]. Do you know what the problem is?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

The arrayWithHeight array is redeclared every render cycle and only a single value is pushed into it. Convert arrayWithHeight to local component state and use a functional state update to retain the previous state values.

React state updates are also asynchronously processed, so trying to use the height state to add to the arrayWithHeight state won't work since it won't have been updated yet. Use the current height ref value instead.

const [height, setHeight] = useState(0);
const [arrayWithHeight, setArrayWithHeight] = useState([]);

const ref = useRef(null);

useEffect(() => {
  setHeight(ref.current.clientHeight);
  addItemsToArray(ref.current.clientHeight);
}, [addItemsToArray]);



function addItemsToArray(height) {
  setArrayWithHeight(heights => [...heights, height]);
}

Update

You've only a single ref, you'd need a ref for each paragraph to get each one's height. The following is a way to store an array of refs and get their computed heights. Spread the array of heights into the Math.Max function to return the maximum height value

const [height, setHeight] = useState(0);

const heightRefs = useRef([]);

heightRefs.current = data.map((_, i) => heightRefs.current[i] ?? createRef());

useLayoutEffect(() => {
  setHeight(
    Math.max(
      ...heightRefs.current.map((el) =>
        Number(getComputedStyle(el.current).height.match(/\d+/).pop())
      )
    )
  );
}, []);

...

<div>
  {data.map((el, i) => (
    <p
      key={el}
      ref={heightRefs.current[i]}   // <-- ref by index
      style={{ minHeight: height }} // <-- set a minimum height
    >
      {el}
    </p>
  ))}
</div>

Edit billowing-water-u0t9jx

about 4 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 Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda