React by Patrik

How to resize an element using the scroll height of the document in React

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

The problem

Suppose 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';

export default const Page = () => {
    return (
        <div className = 'Page'>
            <Nav/>
            <Main/>
        </div>
    );
}

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';

export default 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>
    );
}

Now the main component will expand and the sticky element will work as expected.

Comments

Leave a Comment

All fields are required. Your email address will not be published.