Get Viewport/Window Height in ReactJS

In the dynamic and visually engaging world of web development, understanding and manipulating the viewport or window size can be crucial for creating responsive and user-friendly interfaces.

ReactJS, being one of the most popular JavaScript libraries for building user interfaces, offers several ways to handle viewport sizes effectively.

In this article, we'll dive into how to get the viewport or window height in ReactJS, ensuring your application looks great on any device.

Understanding Viewport Height

Before we get our hands dirty with code, let's clarify what we mean by "viewport height." The viewport is essentially the visible area of a web page that a user can see.

It varies with the device - be it a desktop, tablet, or mobile phone - and also changes when a user resizes their browser window.

Capturing the viewport height allows developers to make decisions based on the amount of space available for rendering the UI.

Accessing Window Height in React

Using window.innerHeight

The most straightforward way to get the viewport height is by using the global window object's innerHeight property. This property returns the height of the window's content area in pixels including scrollbars.

Here's a simple example of how to use window.innerHeight in a React functional component:

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

const App = () => {
  const [windowHeight, setWindowHeight] = useState(window.innerHeight);

  useEffect(() => {
    const handleResize = () => {
      setWindowHeight(window.innerHeight);
    };

    window.addEventListener('resize', handleResize);

    // Cleanup function to remove the event listener
    return () => window.removeEventListener('resize', handleResize);
  }, []);

  return (
    <div>
      <h1>The viewport height is: {windowHeight}px</h1>
    </div>
  );
};

export default App;

In this example, we use the useState hook to store the window height and the useEffect hook to add an event listener for window resize events.

This way, the component automatically updates the displayed height whenever the window is resized.

Considerations for Server-Side Rendering (SSR)

If you're working with a React app that uses server-side rendering (SSR), like Next.js, directly accessing window can lead to errors since window is not defined on the server.

To circumvent this issue, you can check if the window object is available before using it:

const [windowHeight, setWindowHeight] = useState(0); // Default to 0 or a sensible default

useEffect(() => {
  // Ensure window object is available
  if (typeof window !== "undefined") {
    setWindowHeight(window.innerHeight);

    const handleResize = () => {
      setWindowHeight(window.innerHeight);
    };

    window.addEventListener('resize', handleResize);

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

Custom Hooks for Reusability

To make our viewport height functionality more reusable across different components, we can encapsulate it within a custom hook. Here's how you can create a useWindowHeight hook:

import { useState, useEffect } from 'react';

const useWindowHeight = () => {
  const [height, setHeight] = useState(0);

  useEffect(() => {
    if (typeof window !== "undefined") {
      const updateHeight = () => {
        setHeight(window.innerHeight);
      };

      window.addEventListener('resize', updateHeight);
      updateHeight(); // Initialize height

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

  return height;
};

export default useWindowHeight;

Using this hook in a component would look something like this:

import React from 'react';
import useWindowHeight from './useWindowHeight';

const MyComponent = () => {
  const windowHeight = useWindowHeight();

  return <div>Window height is: {windowHeight}px</div>;
};

export default MyComponent;

Conclusion

ReactJS provides flexible ways to access and react to changes in the viewport height, enabling developers to create responsive and adaptable web applications.

Whether you're adjusting layout elements based on the viewport size or implementing dynamic animations, understanding how to retrieve and use the window height is a valuable skill in your React toolbox.

Remember, the key to creating a great user experience is not just about making things work but also about making them work well across all devices and screen sizes. Happy coding!