Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

154
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!