Resize an element using the scroll height of the document in React

Sometimes is useful to know the scroll height of the window. Let's look at an example.

The problem

Let's suppose that we have a component with two elements: a navigator and a main component.

import React from 'react';
import Nav   from './Nav';
import Main  from './Main';

const Page = () => {
    return (
        <div className = 'Page'>

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).

The solution

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.

import 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>

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.