Get viewport/window height in ReactJS Get viewport/window height in ReactJS javascript javascript

Get viewport/window height in ReactJS


Using Hooks (React 16.8.0+)

Create a useWindowDimensions hook.

import { useState, useEffect } from 'react';function getWindowDimensions() {  const { innerWidth: width, innerHeight: height } = window;  return {    width,    height  };}export default function useWindowDimensions() {  const [windowDimensions, setWindowDimensions] = useState(getWindowDimensions());  useEffect(() => {    function handleResize() {      setWindowDimensions(getWindowDimensions());    }    window.addEventListener('resize', handleResize);    return () => window.removeEventListener('resize', handleResize);  }, []);  return windowDimensions;}

And after that you'll be able to use it in your components like this

const Component = () => {  const { height, width } = useWindowDimensions();  return (    <div>      width: {width} ~ height: {height}    </div>  );}

Working example

Original answer

It's the same in React, you can use window.innerHeight to get the current viewport's height.

As you can see here


This answer is similar to Jabran Saeed's, except it handles window resizing as well. I got it from here.

constructor(props) {  super(props);  this.state = { width: 0, height: 0 };  this.updateWindowDimensions = this.updateWindowDimensions.bind(this);}componentDidMount() {  this.updateWindowDimensions();  window.addEventListener('resize', this.updateWindowDimensions);}componentWillUnmount() {  window.removeEventListener('resize', this.updateWindowDimensions);}updateWindowDimensions() {  this.setState({ width: window.innerWidth, height: window.innerHeight });}


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