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. Set up a state variable to store the window width and height.
  3. Attach an event listener to the resize event of the window object to update the state whenever the window size changes.
  4. 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.

JavaScript
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.

JavaScript
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.

JavaScript
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:

JavaScript
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 Posts

React 19 New Features

React 19: New Features and Upcoming Major Releases in 2024

Get ready for some exciting news from the ReactJS official blog! If you love ReactJS, you’re in for a treat. We’ll take you through the latest cool stuff, like the supercharged React Compiler, the game-changing Actions, and new features in React Canary.

building ui elements with jsx

Building UI Elements with JSX and Components

Ready to dive into React? This chapter unlocks the secrets of JSX – writing HTML right in your JavaScript! We’ll also explore components, the reusable powerhouses of React .

Ultimate-Development-Environment-Setup-React.JS

Build React Apps Like a Boss: The Ultimate Development Environment Setup React.JS

Ready to transform static web pages into dynamic experiences? This guide unveils the secrets to setting up your React development environment, from essential tools to project structure. Discover Node.js, npm, and the perfect code editor for you. Equip your editor with powerful extensions for debugging, linting, and more. Learn how to organize your project like a pro and dive into the magic of reusable React components. Don’t wait! Build your foundation, unleash your creativity, and embark on your React journey today!

React 101 Featured

React 101: Your Beginner’s Guide to the Popular JavaScript Library

Dive into the world of React and unlock its potential for building dynamic, interactive web applications. This beginner-friendly guide covers everything you need to know, from core concepts to essential tools.

useeffect vs uselayouteffect

Mastering Your Side Effects: useEffect vs useLayoutEffect in React

React hooks have revolutionized the way we manage state and side effects in our components. But when it comes to side effects, two power players emerge: useEffect…

react-fiber

React Fiber: The Secret Sauce Behind Blazing-Fast React Apps

Discover the magic of React Fiber – the secret superhero enhancing React’s speed and intelligence. Analogous to an artist carefully drawing changes, Fiber’s behind-the-scenes tricks optimize rendering. Unlike the previous version, Fiber slices tasks, preventing app slowdowns during updates. This superhero ensures your app stays swift and responsive, making coding a seamless experience. Dive into the superhero world of React Fiber and level up your coding skills with the React docs. 🚀

Leave a Reply

Your email address will not be published. Required fields are marked *