Ian Springer
Ian Springer

Reputation: 233

Get Height of document in React

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!

Upvotes: 3

Views: 20288

Answers (3)

thielr7
thielr7

Reputation: 337

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!

Upvotes: 10

Its worker for me:

document.documentElement.offsetHeight

Upvotes: 4

thinhvo0108
thinhvo0108

Reputation: 2232

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(){
        // ...
    }

}

Upvotes: 1

Related Questions