How do I get the viewport height in ReactJS? In normal JavaScript I use
JavaScript
x
2
1
window.innerHeight()
2
but using ReactJS, I’m not sure how to get this information. My understanding is that
JavaScript
1
2
1
ReactDOM.findDomNode()
2
only works for components created. However this is not the case for the document
or body
element, which could give me height of the window.
Advertisement
Answer
JavaScript
1
16
16
1
class AppComponent extends React.Component {
2
3
constructor(props) {
4
super(props);
5
this.state = {height: props.height};
6
}
7
8
componentWillMount(){
9
this.setState({height: window.innerHeight + 'px'});
10
}
11
12
render() {
13
// render your component...
14
}
15
}
16
Set the props
JavaScript
1
8
1
AppComponent.propTypes = {
2
height:React.PropTypes.string
3
};
4
5
AppComponent.defaultProps = {
6
height:'500px'
7
};
8
viewport height is now available as {this.state.height} in rendering template