React window.innerWidth
and window.innerHeight
properties allow users to get height and width of window screen, In this tutorial, you will learn how to detect the dynamic window width and height on window resize using react useState and use effect hooks.
How to Get/Detect Window Size(Height & Width) in React Js
Here are steps to get window size:
Step 1 – Create React App
In this step, open your cmd and run the following command on your terminal to create a new react app:
npx create-react-app my-react-app
To run the React app, execute the following command on your terminal:
npm start
Check out your React app on this URL: localhost:3000
Step 2 – Create Simple Component
Go to the src
directory of your react js app, create get dynamic height and width component named UserWindow.js:
import React, { Component } from "react";
class UserWindow extends Component {
render() {
return (
<> </>
);
}
}
export default UserWindow;
Then implement code to detect window height width on window resize; as shown below:
import React, { useState, useEffect } from 'react'
export default function UserWindow() {
const [screenSize, getDimension] = useState({
dynamicWidth: window.innerWidth,
dynamicHeight: window.innerHeight
});
const setDimension = () => {
getDimension({
dynamicWidth: window.innerWidth,
dynamicHeight: window.innerHeight
})
}
useEffect(() => {
window.addEventListener('resize', setDimension);
return(() => {
window.removeEventListener('resize', setDimension);
})
}, [screenSize])
return (
<div>
<ul>
<li>Width: <strong>{screenSize.dynamicWidth}</strong></li>
<li>Height: <strong>{screenSize.dynamicHeight}</strong></li>
</ul>
</div>
)
}
Step 3 – Add Component in App.js
In this step, you need to add UserWindow.js file in src/App.js
file:
import React from 'react';
import './App.css';
import UrlComponent from './components/UrlComponent';
function App() {
return (
<div className="App">
<UrlComponent />
</div>
);
}
export default App;
Conclusion
In this tutorial, you have learned how to detect or get dynamic window height and width in react js application.