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?
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]);
}
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>