How to Get Window Width in React
This article will demonstrate how to find the window width value in React.
Responsiveness is one of the foundations of modern web development. These days, people browse websites from many different devices: laptops, desktops, mobile phones, and even gaming consoles.
Responsiveness means responding to the user’s needs and adjusting the layout of your application based on the user’s device.
Get Window Width in React
The most important feature of any device is its screen size. In React application, we can easily access the number representing screen size in pixels.
Then we can use this information to change the appearance and functionality of our React app. You could use the screen size (in pixels) to apply classes conditionally.
For instance, if the window width is under 600px, have a padding of 10px, and if it’s over 600px, have a padding of 20px. In short, you could use the screen width to check how well the content fits on your page.
We can store the window width value in the component state. If the window width changes during runtime, you can set up your React application to set the state value to the updated width.
Get Window Width in React Class Components
In class components, we need to use the .addEventListener()
method to listen for resize
event on the window
object itself. Anytime the user changes the window’s width, the event handler is executed, updating the window width value.
Code:
constructor(props) {
super(props);
this.state = { windowWidth: 0, windowHeight: 0 };
this.handleResize = this.handleResize.bind(this);
}
componentDidMount() {
this.handleResize();
window.addEventListener('resize', this.handleResize);
}
componentWillUnmount() {
window.removeEventListener('resize', this.handleResize);
}
handleResize() {
this.setState({ windowWidth: window.innerWidth, windowHeight: window.innerHeight });
}
First, we start by initiating the state and setting the windowWidth
and windowHeight
properties to a default value of 0. We also bind the handleResize
method.
In the componentDidMount()
lifecycle method, we call the handleResize()
method for the first time. This will set the initial dimensions of our page and a handler for the resize
event.
In the componentWillUnmount
lifecycle method, we remove the event listener.
Finally, we use the innerWidth
property of the window object to access the width of a window. We use the innerHeight
property to capture the height.
We use the setState()
method to update the state of the class component and set state properties to these dimensions.
Get Window Width in React Function Components
In function components, you can create a custom useWindowDimensions
hook and then use it to get the window width and height values easily.
Let’s look at the definition of the useWindowDimensions
hook.
Code:
import { useState, useEffect } from 'react';
function getWindowDimensions() {
const width = window.innerWidth
const height = window.innerHeight
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;
}
Then we use the useEffect
hook imported from the core React library to perform the same tasks as we did in lifecycle components: add an event listener and run it once to get initial window dimensions when the component mounts, and remove the event listener when it unmounts.
Once set up, you can import the useWindowDimensions
hook within other components and use it to obtain the width and height of a window easily.
Code:
const App = () => {
const { height, width } = useWindowDimensions();
return (
<div>
The width of your window: {width}
The height of your window: {height}
</div>
);
}
Irakli is a writer who loves computers and helping people solve their technical problems. He lives in Georgia and enjoys spending time with animals.
LinkedIn