How to Toggle a Div to Fullscreen in React

Building responsive, interactive applications in React often requires creating components that dynamically change based on user interaction. One common feature is allowing a div to take over the entire screen with the click of a button, creating a fullscreen effect.

Thank me by sharing on Twitter 🙏

In this post, I’ll walk through how to implement this feature, making sure to keep the code clean, reusable, and easy to maintain.

Why You Might Want a Fullscreen Toggle

There are plenty of scenarios where you might want an element to fill the entire screen. A few examples:

  • A modal that needs to take up the full screen for a better user experience on mobile devices.
  • A media player that can switch between regular and fullscreen modes.
  • A dashboard or chart that users can zoom into for better readability.

Having the flexibility to make any element fullscreen allows us to create more dynamic and immersive user experiences.

Setting Up the Component with React and TypeScript

For this feature, we’ll use the useState hook to manage whether the div is fullscreen or not. Using TypeScript ensures that our types are always in check and reduces potential errors.

Here’s what we need:

  1. A button that toggles the fullscreen mode.
  2. A div that will resize to fill the viewport when fullscreen is enabled.
  3. Some simple CSS to handle the transitions smoothly.

Let’s start by creating a FullScreenToggle component.

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

const FullScreenToggle: React.FC = () => {
  const [isFullScreen, setIsFullScreen] = useState<boolean>(false);

  const toggleFullScreen = () => {
    setIsFullScreen(!isFullScreen);
  };

  return (
    <div>
      <button onClick={toggleFullScreen}>
        {isFullScreen ? 'Exit Fullscreen' : 'Go Fullscreen'}
      </button>

      <div
        className={`box ${isFullScreen ? 'fullscreen' : ''}`}
      >
        This is the content inside the box.
      </div>
    </div>
  );
};

export default FullScreenToggle;

Here’s what’s happening in the code:

  • We declare a state variable isFullScreen to track whether the div is in fullscreen mode or not.
  • A button toggles this state when clicked.
  • Depending on the state, we conditionally apply the fullscreen CSS class to the div, allowing it to switch between regular and fullscreen mode.

The state is managed using the useState hook, which lets us easily update the UI in response to user interaction.

Adding the Fullscreen Styles

For this to work visually, we’ll need to add some CSS. We want the div to take up the full width and height of the viewport when fullscreen is active, but it should retain its original dimensions otherwise.

Here’s the CSS:

CSS
.box {
  width: 300px;
  height: 300px;
  background-color: lightblue;
  margin: 20px auto;
  text-align: center;
  display: flex;
  justify-content: center;
  align-items: center;
  transition: width 0.3s ease, height 0.3s ease;
}

.fullscreen {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  background-color: lightcoral;
  z-index: 999;
}

A few important things to note here:

  • The .box class defines the default size and appearance of the div. It’s set to be a square with a width and height of 300px, centered on the screen.
  • The .fullscreen class applies position: fixed to make the element fill the viewport. It also sets width and height to 100vw and 100vh (viewport width and height) to achieve the fullscreen effect.
  • The transition ensures that the switch between fullscreen and normal mode is smooth.

The Fullscreen Toggle Functionality

Let’s take a closer look at the functionality of the button and the toggleFullScreen function. The button’s text dynamically changes based on whether the div is fullscreen or not, and clicking the button triggers a state change.

Here’s how the state toggle works:

TypeScript
const toggleFullScreen = () => {
  setIsFullScreen(!isFullScreen);
};

The setIsFullScreen function toggles the state between true and false, which is then used to conditionally apply the fullscreen class to the div.

If isFullScreen is true, the div will expand to cover the entire viewport. If isFullScreen is false, the div will return to its default size.

Enhancing the User Experience

While the basic functionality is working, there are a few enhancements you can make for better usability:

  • Keyboard Accessibility: Allow users to press the Esc key to exit fullscreen mode.
  • Animation: Add smoother transitions or animations to make the fullscreen toggle feel more polished.

For keyboard accessibility, you can add an event listener to handle the Esc key. Here’s how to add that functionality:

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

const FullScreenToggle: React.FC = () => {
  const [isFullScreen, setIsFullScreen] = useState<boolean>(false);

  const toggleFullScreen = () => {
    setIsFullScreen(!isFullScreen);
  };

    const handleKeyDown = useCallback(
    (event: KeyboardEvent) => {
      if (event.key === "Escape" && isFullScreen) {
        setFullscreen(false);
      }
    },
    [fullscreen]
  );

  useEffect(() => {
    document.addEventListener("keydown", handleKeyDown);
    return () => {
      document.removeEventListener("keydown", handleKeyDown);
    };
  }, [isFullScreen, handleKeyDown]);
  
  return (
    <div>
      <button onClick={toggleFullScreen}>
        {isFullScreen ? 'Exit Fullscreen' : 'Go Fullscreen'}
      </button>

      <div
        className={`box ${isFullScreen ? 'fullscreen' : ''}`}
      >
        This is the content inside the box.
      </div>
    </div>
  );
};

export default FullScreenToggle;

In this example:

  • We use the useEffect hook to attach an event listener to the document. This listener checks if the Esc key is pressed and exits fullscreen mode if the div is currently fullscreen.
  • When the component unmounts, we remove the event listener to avoid memory leaks.

This enhancement ensures a smoother user experience, especially for those who might expect fullscreen mode to behave like a native application.

Conclusion

In this tutorial, I walked through the process of creating a toggleable fullscreen div in React, complete with responsive state management and smooth CSS transitions. By using the useState hook and conditional class application, we were able to build a simple yet effective feature.

You can further enhance this with accessibility features or more complex animations, depending on the needs of your project. With these steps, adding a fullscreen toggle to your React applications is quick and easy!

Share this:

Leave a Reply