Let's suppose that we are working with a parent/children component:
jsximport React from 'react'; const App = () => { return( <div className = 'Parent'> <h2>I'm the parent.</h2> <p>I have height and width.</p> <div className = 'Children'> <p>I'm the child.</p> <p>I have height and width as well.</p> </div> </div> ); } export default App;
Both components have their own height and width. To determine these parameters, we can use the useRef
Hook.
This Hook creates a reference to the block and enables to access its properties.
jsximport React, { useRef } from 'react'; const App = () => { const parentRef = useRef(null); const childrenRef = useRef(null); return( <div className = 'Parent' ref = { parentRef }> <h2>I'm the parent.</h2> <p>I have height and width.</p> <div className = 'Children' ref = { childrenRef }> <p>I'm the child.</p> <p>I have height and width as well.</p> </div> </div> ); } export default App;
As on first render both references are null, we need to use the useEffect
Hook to get the properties of both elements. Then, we will be able to access height
and width
properties.
jsximport React, { useRef, useEffect } from 'react'; const App = () => { const parentRef = useRef(null); const childrenRef = useRef(null); useEffect ( () => { if(parentRef.current){ let parentHeight = parentRef.current.offsetHeight; let parentWidth = parentRef.current.offsetWidth; } if(childrenRef.current){ let childrenHeight = childrenRef.current.offsetHeight; let childrenWidth = childrenRef.current.offsetWidth; } }, [parentRef, childrenRef]); return( <div className = 'Parent' ref = { parentRef }> <h2>I'm the parent.</h2> <p>I have height and width.</p> <div className = 'Children' ref = { childrenRef }> <p>I'm the child.</p> <p>I have height and width as well.</p> </div> </div> ); } export default App;
Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.