How to Get Screen Width and Height in React JS?

Sep 27, 2022 . Admin

Hello Friends,

Here, I will show you how to work how to get screen width and height in react js. you can see how to get screen size in react js. I would like to share with you react js screen width and height. Here you will learn react screen width. you will do the following things for react screen height.

In this example, we will use "window" object to get screen height and width in react js app. we will use "useState()" and "today.useEffect()" to getting screen width and height on change.

So, let's see follow the below step to create simple example.

Step 1: Create React JS App

In this step, open your terminal and execute the following command on your terminal to create a new react app:

npx create-react-app react-my-example
Step 2: Update App.js Component

Here, we will call two apis for getting posts and another for deleting post using axios request.

src/App.js
import './App.css';
import { useState, useEffect } from "react";

function App() {
  
  const [size, setSize] = useState({
    width: window.innerWidth,
    height: window.innerHeight
  });

  const updateSize = () =>
    setSize({
      width: window.innerWidth,
      height: window.innerHeight
    });

  useEffect(() => (window.onresize = updateSize), []);

  return (
    <div className="App">
      <h1>How to Get Screen Width and Height in React JS? - MyWebtuts.com</h1>
      <h2>Your Window Width and Height are: </h2>
      <h2>width is : { size.width }</h2>
      <h2>height is : { size.height }</h2>
    </div>
  );
}

export default App;
Step 4: Run React JS App

In the last step run your project using bellow command.

npm start
Output

I hope it can help you...

#React JS