To get the window width and height in React, use the window object’s innerWidth and innerHeight properties respectively. To get the viewport window width and height even when the window size gets changed, then follow the below steps.
- Use the window object’s innerWidth and innerHeight properties of the current viewport.
- Set up a state variable to store the window width and height.
- Attach an event listener to the
resize
event of thewindow
object to update the state whenever the window size changes. - Clean up the event listener when the component is unmounted.
Use the window object’s innerWidth and innerHeight properties of the current viewport
The Window property innerWidth returns the inner width of the window in pixels. This includes the width of the vertical scroll bar if it is present in the window. The Window property innerHeight is taken from the height of the window’s layout viewport in pixels, including the height of the horizontal scroll bar if it is present.
We created a function to get the width and height of the current viewport using the below function.
function getCurrentDimension(){
return {
width: window.innerWidth,
height: window.innerHeight
}
}
Store the values in a state
We initialized a state variable called screenSize using the useState React hook that will be updated whenever the height or width of the window changes. The initial state will be the current dimension.
const [screenSize, setScreenSize] = useState(getCurrentDimension());
Add an event listener for the resize event inside the useEffect hook
Next, we want to add an event listener for the resize event in the useEffect hook. When the window gets resized, the new width and height will be updated in the state.
useEffect(() => {
const updateDimension = () => {
setScreenSize(getCurrentDimension())
}
window.addEventListener('resize', updateDimension);
return(() => {
window.removeEventListener('resize', updateDimension);
})
}, [screenSize])
We have returned a removeEventListener
function to remove the event listener when the component unmounts.
Our final code will be:
import React, { useState, useEffect } from 'react'
export default function App() {
const [screenSize, setScreenSize] = useState(getCurrentDimension());
function getCurrentDimension(){
return {
width: window.innerWidth,
height: window.innerHeight
}
}
useEffect(() => {
const updateDimension = () => {
setScreenSize(getCurrentDimension())
}
window.addEventListener('resize', updateDimension);
return(() => {
window.removeEventListener('resize', updateDimension);
})
}, [screenSize])
return (
<div>
<ul>
<li>Width: <strong>{screenSize.width}</strong></li>
<li>Height: <strong>{screenSize.height}</strong></li>
</ul>
</div>
)
}
Conclusion
In this article, we have learned how to get window width and height in React. For this use the window object’s innerWidth and innerHeight properties to get the width and height current viewport.