Trying to use scrollHeight in react

Viewed 20788

Can anyone tell me why I'm getting undefined when I console.log heightSet?

componentDidMount() {
    this.updateDimensions();
    window.addEventListener('resize', this.updateDimensions.bind(this));
}

componentWillUnmount() {
    window.removeEventListener('resize', this.updateDimensions.bind(this));
}

updateDimensions() {
    this.setState({ heightSet: document.scrollHeight });
    console.log(document.clientHeight);
}

the same console.log worked for window.innerHeight (clientHeight gets undefined as well) but I don't want inner height I want scrollHeight.

thanks

2 Answers

scrollHeight is a property on Element so I guess you maybe want document.body.scrollHeight.

By the way, every time you called this.updateDimensions.bind(this) you get a new function, so you can't use this approach to add and remove the same event listener.

You should add a constructor to your class, containing the following:

constructor(props) {
    super(props);
    this.updateDimensions = this.updateDimensions.bind(this);
}

Then you can add/remove this.updateDimensions directly:

componentDidMount() {
    this.updateDimensions();
    window.addEventListener('resize', this.updateDimensions);
}

componentWillUnmount() {
    window.removeEventListener('resize', this.updateDimensions);
}

updateDimensions() {
    this.setState({ heightSet: document.body.scrollHeight });
}

You may want to try to use the "scroll" event instead.

componentDidMount() {
    this.updateDimensions();
    window.addEventListener('scroll', this.updateDimensions);
}

componentWillUnmount() {
    window.removeEventListener('scroll', this.updateDimensions);
}

updateDimensions() {
    this.setState({ heightSet: window.scrollY });
}
Related