Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

Get viewport/window height in ReactJS

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 the height of the window.
by

4 Answers

espadacoder11
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>
);
}
sandhya6gczb
It also handles window resizing

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 });
}
RoliMishra
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
hackeracademy
Good post. I wanna to try this react script for my webpage. Thanks

Login / Signup to Answer the Question.