How to get the width of the window in React.js

When dealing with UI elements in React.js sometimes we find ourselves conditionally rendering some JSX elements based on the size of the viewports window.

In these situations, it’s important to have the exact dimensions of the window. So, how do you get the width of the window in React.js. Thankfully, this is the same as any other JavaScript application. We can accomplish this using the following:

class Main extends React.Component {
 constructor(props) {
    super(props);
    this.state = { windowWidth: window.innerWidth };
  }

 const handleResize = (e) => {
  this.setState({ windowWidth: window.innerWidth });
 };

 componentDidMount() {
  window.addEventListener("resize", this.handleResize);
 }

 componentWillUnMount() {
  window.addEventListener("resize", this.handleResize);
 } 

  render() {
    const { windowWidth } = this.state; 
    return <div>Current window width: {windowWidth}</div>
  }
}
  • We are setting the default value of windowWidth using the layout’s viewport value of window.innerWidth.
  • In componentDidMount and componentWillUnmount we are setting the resize event listener. This allows us to get the updated window width value whenever the screen is resized
  • And finally, handleResizewill update the state value of windowWidth when that resize event fires.

Ideally, you want to check this after the component has mounted in order to get the accurate width value. 

So there you have it. Detecting the width with this approach will give you dynamic control of your UI.

Gareth Dunne

Senior JavaScript Engineer and creator of JSdiaries. Passionate about the latest in web technologies and how it can provide value for my clients.