Reputation: 83
I'm trying to get the scrollHeight of an element to add a padding to the bottom if it's higher than the offsetHeight but I get in both cases the same value like if the element has not rendered completely or something.
This is how i set it up:
componentDidMount(){
this.checkHeight();
}
componentDidUpdate() {
this.checkHeight();
}
checkHeight = () => {
if(this.section){
window.section = this.section;
console.log(this.section.offsetHeight, this.section.scrollHeight, ReactDOM.findDOMNode(this.section).scrollHeight);
}
};
render() {
return (
<section className={classes.Admin}>
<ul className={classes.Navbar}>
<NavbarItem link="/admin" exact clicked={this.changeSectionHandler}>Main</NavbarItem>
<NavbarItem link={this.props.match.url + '/users'} clicked={this.changeSectionHandler}>Users</NavbarItem>
</ul>
<div className={classes.Section} ref={section => this.section = section}>
<Switch>
<Route path={this.props.match.url} exact component={Main}/>
<Route path={this.props.match.url + '/users'} exact component={Users}/>
<Route path={this.props.match.url + '/users/:id'} exact component={Users}/>
<Route path={this.props.match.url + '/users/add'} exact component={Users}/>
<Redirect to="/admin"/>
</Switch>
</div>
</section>
);
}
If i get the values of section.offsetHeight and section.scrollHeight in the console after i loaded the page, they are correct.
I'm definitely stuck here, I learned that componentDidMount get fired only when inner components are mounted but I don't know about componentDidUpdate so I guess the problem is there (when I open the scrollable page the componentDidUpdate function is fired, the componentDidMount is useless for the time being).
Upvotes: 2
Views: 3290
Reputation: 2065
I think it's because when React events fire, actual onscreen rendering is not quite finished (it's not that I'm stating it, it's only my suggestion).
Try to do
componentDidMount(){
setTimeout(this.checkHeight, 0);
}
componentDidUpdate(){
setTimeout(this.checkHeight, 0);
}
Upvotes: 4