Sometimes is useful to know the scroll height of the window. Let's look at an example.
Let's suppose that we have a component with two elements: a navigator and a main component.
jsximport React from 'react'; import Nav from './Nav'; import Main from './Main'; const Page = () => { return ( <div className = 'Page'> <Nav/> <Main/> </div> ); } export default Page;
Let's suppose that Page.js
is a flex-box, Nav.js
is a sticky element and Main.js
has a position: absolute
element inside of it.
If the element with absolute position is larger than the size of main, the sticky navigator will not work as expected (it won't stick).
We'll need to resize the Main.js
component and make it as big as the scroll height of the window. To do so, we need to read scrollHeight
property.
jsximport React, { useEffect, useState } from 'react'; const Main = () => { const [height, setHeight] = useState(0); useEffect( () => { setHeight(document.documentElement.scrollHeight) }); return ( <div className = 'Main' style = {{height: `${height}px`}}> <div className = 'Absolute'>This is an absolute positioned element.</div> </div> ); } export default Main;
Now the main component will expand and the sticky element will work as expected.
Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.