2

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?

4

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

9 Comments

I get array for each height (9879) [113, 113, 113, 113, 113, 113, 113, 113, 113, 113, 113, 113, 113, 113, 113, 113, 113, 113, 113, 113, 113, 113, 113, 113, 113, 113, 113, 113, 113, 113, 113, 113, 113, 113, 113, 113, 113, 113, 113, 113, 113, 113, 113, 113, 113, 113, 113, 113, 113, 113, 113, 113, 113, 113, 113, 113, 113, 113, 113, 113, 113, 113, 113, 113, 113, 113, 113, 113, 113, 113, 113, 113, 113, 113, 113, 113, 113, 113, 113, 113, 113, 113, 113, 113, 113, 113, 113, 113, 113, 113, 113, 113, 113, 113, 113, 113, 113, 113, 113, 113, …]
@Elder Eh, yeah, looking at the code with more context it doesn't make a lot of sense. addItemsToArray is redeclared each render cycle, and will trigger the useEffect hook callback and likely create a render loop. What is this component rendering and what is the ref attached to? Can you post a more complete code example? stackoverflow.com/help/minimal-reproducible-example When do you actually want to set the height state and update the heights array?
I want to collect the height of all the paragraphs on the page and make them equal height.
@Elder You've only a single ref, you'd need a ref for each paragraph to get each one's height. Are you mapping these paragraphs from some other data? Are you wanting to grab the size of the biggest paragraph? The smallest?
@Elder I've added to my answer handling an array of React refs. Please check it out.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.