PASSWORD RESET

Your destination for complete Tech news

How to get the size of the screen in React JS?

366 0
< 1 min read

To get the size of the screen in a React component, you can use the window.innerWidth and window.innerHeight properties. Here’s how you can do it:

import React, { useState, useEffect } from 'react';

function ScreenSize() {
  const [screenWidth, setScreenWidth] = useState(window.innerWidth);
  const [screenHeight, setScreenHeight] = useState(window.innerHeight);

  useEffect(() => {
    const handleResize = () => {
      setScreenWidth(window.innerWidth);
      setScreenHeight(window.innerHeight);
    };

    window.addEventListener('resize', handleResize);

    return () => {
      window.removeEventListener('resize', handleResize);
    };
  }, []);

  return (
    <div>
      <p>Screen Width: {screenWidth}px</p>
      <p>Screen Height: {screenHeight}px</p>
    </div>
  );
}

export default ScreenSize;

In this example, the ScreenSize component uses the useState and useEffect hooks to track the screen width and height. The useEffect hook listens for the resize event on the window object and updates the state with the current screen width and height when the window is resized.

The component then displays the current screen width and height in pixels.

Keep in mind that using the resize event to track screen size changes can be resource-intensive. Consider using debouncing or throttling techniques to optimize the event handling, especially if your application needs to handle frequent resizing events.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.