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?
console.logs. In this case, you should just be using two separate refs for each paragraph. If you need to be more dynamic, you should look at dev.to/oussel/a-guide-for-refs-in-react-45l6#chapter-1