Categories
React Answers

How to Get the Viewport or Window Height in React?

Spread the love

Sometimes, we want to get the viewport or window height with React.

In this article, we’ll look at how to get the viewport or window height with React.

Get the Viewport or Window Height in React

To get the viewport or window height with React, we can add the resize listener into our React app.

For instance, we can write:

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

const getWindowDimensions = () => {
  const { innerWidth: width, innerHeight: height } = window;
  return {
    width,
    height
  };
};

const useWindowDimensions = () => {
  const [windowDimensions, setWindowDimensions] = useState(
    getWindowDimensions()
  );

  useEffect(() => {
    function handleResize() {
      setWindowDimensions(getWindowDimensions());
    }

  window.addEventListener("resize", handleResize);
    return () => window.removeEventListener("resize", handleResize);
  }, []);

  return windowDimensions;
};

export default function App() {
  const { height, width } = useWindowDimensions();

  return (
    <div>
      width: {width} x height: {height}
    </div>
  );
}

to add the useWindowDimensions hook that calls the useEffect hook with a callback that adds the resize event on window into our app.

We call window.addEventListener to add the resize event listener.

And then we call getWindowDimensions to get the window dimensions.

We get the window.innerHeight to get the height of the viewport or window.

And innerWidth gets the width of it.

We call setWindowDimensions on with the object returned by getWindowDimensions .

Then we use the useWindowDimensions hook in our App component to render the height and width .

Now when we resize the viewport, we see the dimension numbers change.

Conclusion

To get the viewport or window height with React, we can add the resize listener into our React app.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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