/  Technology   /  Re-render the view when the browser is resized in React js
Re-render the view when the browser is resized in React js

Re-render the view when the browser is resized in React js

 

We can re-render the view when the browser is resized in react using the below example. Resizing browser view can be done using javascript logic and react hooks. In the below example we have used the functional component, but the same results can be achieved using class components as well. 

import React, { useEffect, useState } from "react";
const Text = () => {
  const [windowWidth, setWindowWidth] = useState(0);
  const [windowHeight, setWindowHeight] = useState(0);
  let resizeWindow = () => {
    setWindowWidth(window.innerWidth);
    setWindowHeight(window.innerHeight);
  };
  useEffect(() => {
    resizeWindow();
    window.addEventListener("resize", resizeWindow);
    return () => window.removeEventListener("resize", resizeWindow);
  }, []);
  return (
    <div>
      <span>
        {windowWidth} x {windowHeight}
      </span>
    </div>
  );
};
export default Text;

Using the above code we will be able to resize any window in react js. 

Here we have firstly declared state windowWidth and windowHeight initially as 0. Then we are setting the windowWidth and height using the javascript window.innerwidth and height method. In the useEffect we have called resizeWindow() function and passed this function in the window.addEventListener() and after the function is executed we are removing the eventListener.

Lastly in the span tag for displaying on the UI we are dynamically calling {window.height} and {window.width} which display’s us the width and height of the screen. 

Output :

Re-render the view when the browser is resized in React js

 

Leave a comment