How to get window width and height in React

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.

  1. Use the window object’s innerWidth and innerHeight properties of the current viewport.
  2. Store the values in a state.
  3. Add an event listener for the resize event inside the useEffect hook and update the new width and height in the state variable.

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.

Related Blogs

Can't Perform a React State Update on an Unmounted Component

Can't Perform a React State Update on an Unmounted Component

React Warning “Can't perform a react state update on an unmounted component” is caused when we try to update the state after the component was unmounted. Explains how to fix it.

Each child in a list should have a unique key prop

Each child in a list should have a unique key prop

Solve Warning: Each child in a list should have a unique ”key" prop in React by setting the id property as a unique key or by auto-assigning unique keys.

React Hook is Called Conditionally

React Hook is Called Conditionally

Error: "React Hook is called conditionally. React Hooks must be called in the exact same order in every component render" occurs when hooks are invoked conditionally or after a return of a value.

Too many re-renders. React limits the number of renders to prevent an infinite loop

Too many re-renders. React limits the number of renders to prevent an infinite loop

The React error "Too many re-renders. React limits the number of renders to prevent an infinite loop" happens when you have reached an infinite render loop.

Adjacent JSX elements must be wrapped in an enclosing tag

Adjacent JSX elements must be wrapped in an enclosing tag

The "Adjacent JSX elements must be wrapped in an enclosing tag" error can be solved by wrapping the multiple elements in a parent div or in a react fragment

The tag is unrecognized in this browser

Warning: The tag is unrecognized in this browser

Warning "The tag is unrecognized in this browser" occurs when the tag doesn't exist in the browser or when we render a component starting with a lowercase letter.

The style prop expects a mapping from style properties to values, not a string

The style prop expects a mapping from style properties to values, not a string

"The style prop expects a mapping from style properties to values, not a string" React error occurs when we pass a CSS string to the style attribute.

Pass event and parameter onClick in React

How to pass event and parameter onClick in React

We set the inline arrow function (event) => clickHandler(event, "Hello World!") as props to the onClick event handler in the button. The arrow function takes the event as an argument and calls the clickHandler function.

Create a Back button with React Router

Create a Back button with React Router

To create a back button with React Router use useNavigate() hook. Call navigate function eg. navigate(-1); inside the onClick function of the back button.