Get Height of document in React

11,657

Solution 1

I just spent some serious time figuring some things out with React and scrolling events / positions - so for those still looking, here's what I found:

The viewport height can be found by using window.innerHeight or by using document.documentElement.clientHeight. (Current viewport height)

The height of the entire document (body) can be found using window.document.body.offsetHeight.

If you're attempting to find the height of the document and know when you've hit the bottom - here's what I came up with:

if (window.pageYOffset >= this.myRefII.current.clientHeight &&
  Math.round((document.documentElement.scrollTop + window.innerHeight))
  < document.documentElement.scrollHeight - 72) {
    this.setState({ trueOrNot: true });
  } else {
    this.setState({ trueOrNot: false });
  }
}

(My navbar was 72px in fixed position, thus the -72 to get a better scroll-event trigger)

Lastly, here are a number of scroll commands to console.log(), which helped me figure out my math actively.

console.log('window inner height: ', window.innerHeight);

console.log('document Element client hieght: ', document.documentElement.clientHeight);

console.log('document Element scroll hieght: ', document.documentElement.scrollHeight);

console.log('document Element offset height: ', document.documentElement.offsetHeight);

console.log('document element scrolltop: ', document.documentElement.scrollTop);

console.log('window page Y Offset: ', window.pageYOffset);

console.log('window document body offsetheight: ', window.document.body.offsetHeight);

Whew! Hope it helps someone!

Solution 2

Its worker for me:

document.documentElement.offsetHeight

Solution 3

Finding the height of document on page load is a too tricky, in my opinion! However, finding it after page has loaded is kind of an easier task. Therefore, try to find it in the "componentDidMount()" function! You can either use:

  • document.documentElement.offsetHeight
  • $(document).height()

(The truth is React also has a built-in version of jQuery, so you can actually use the second way to get the height)

For example:

import React, {Component} from 'react';

export default class YourClass extends Component {
    constructor(props){
        super(props);
        // ...
    }

    componentDidMount() {
        console.log("document-height",document.documentElement.offsetHeight);
        console.log("jQuery-document-height",$(document).height());
    }

    render(){
        // ...
    }

}
Share:
11,657
Ian Springer
Author by

Ian Springer

Updated on June 04, 2022

Comments

  • Ian Springer
    Ian Springer almost 2 years

    How do you find the height of the entire document on page load in React? So in jQuery it would look something like:

    $(document).height();
    

    Thanks for your help!