HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptreactMajor

Get viewport/window height in ReactJS

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
getwindowreactjsheightviewport

Problem

How do I get the viewport height in ReactJS? In normal JavaScript I use

window.innerHeight()


but using ReactJS, I'm not sure how to get this information. My understanding is that

ReactDOM.findDomNode()


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.

Solution

class AppComponent extends React.Component {

  constructor(props) {
    super(props);
    this.state = {height: props.height};
  }

  componentWillMount(){
    this.setState({height: window.innerHeight + 'px'});
  }

  render() {
    // render your component...
  }
}



Set the props

AppComponent.propTypes = {
 height:React.PropTypes.string
};

AppComponent.defaultProps = {
 height:'500px'
};



viewport height is now available as {this.state.height} in rendering template

Code Snippets

class AppComponent extends React.Component {

  constructor(props) {
    super(props);
    this.state = {height: props.height};
  }

  componentWillMount(){
    this.setState({height: window.innerHeight + 'px'});
  }

  render() {
    // render your component...
  }
}
AppComponent.propTypes = {
 height:React.PropTypes.string
};

AppComponent.defaultProps = {
 height:'500px'
};

Context

Stack Overflow Q#36862334, score: 68

Revisions (0)

No revisions yet.