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.
Nexus: A Brief History of Information Networks from the Stone Age to AI
$22.45 (as of November 20, 2024 11:11 GMT +00:00 - More infoProduct prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on [relevant Amazon Site(s), as applicable] at the time of purchase will apply to the purchase of this product.)Anker USB C to USB C Cable, Type C 60W Fast Charging Cable (6FT, 2Pack) for iPhone 16 Series, iPad Mini 6 and More (USB 2.0, Black)
$9.99 (as of November 20, 2024 06:18 GMT +00:00 - More infoProduct prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on [relevant Amazon Site(s), as applicable] at the time of purchase will apply to the purchase of this product.)Apple USB-C to Lightning Cable (1 m)
$15.99 (as of November 20, 2024 06:18 GMT +00:00 - More infoProduct prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on [relevant Amazon Site(s), as applicable] at the time of purchase will apply to the purchase of this product.)Here’s what we need:
- A button that toggles the fullscreen mode.
- A
div
that will resize to fill the viewport when fullscreen is enabled. - Some simple CSS to handle the transitions smoothly.
Let’s start by creating a FullScreenToggle
component.
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 thediv
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 thediv
, 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:
.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 thediv
. It’s set to be a square with a width and height of 300px, centered on the screen. - The
.fullscreen
class appliesposition: fixed
to make the element fill the viewport. It also setswidth
andheight
to100vw
and100vh
(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:
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:
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 thedocument
. This listener checks if theEsc
key is pressed and exits fullscreen mode if thediv
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!