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

155
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
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