snippet
useFullscreen
snippet
useFullscreen
Last updated August 3rd, 2023
Picture this: You have a stunning image gallery, a captivating video player, or an awe-inspiring presentation that deserves the spotlight. With the "useFullscreen" hook, you can easily take your user's focus to the next level by allowing them to enjoy your content in fullscreen mode with just a simple click.
The "useFullscreen" hook wraps the browser's fullscreen API, making it a breeze to toggle fullscreen mode for a specific element and all its descendants. By utilizing this hook, you're offering your users a more engaging, focused, and uninterrupted experience, thus leaving a lasting impression on your web application.
The useFullscreen hook returns an array consisting on two elements:
In the following example we've created an ImageGallery component that displays three images. By utilizing the useFullscreen hook, we enable users to view these images in fullscreen mode when clicked.
Now, when a user clicks on any image in the gallery, it will instantly expand to fullscreen mode. When clicked again or if the user presses the "Esc" key, the image will return to its original size.
import { useRef, useCallback } from "react";
const useFullscreen = () => {
const elementRef = useRef(null);
const toggleFullscreen = useCallback(() => {
if (!document.fullscreenElement) {
elementRef.current?.requestFullscreen();
} else if (document.exitFullscreen) {
document.exitFullscreen();
}
}, []);
return [elementRef, toggleFullscreen];
};
import React from "react";
import useFullscreen from "./useFullscreen";
const ImageGallery = () => {
const [imageRef, toggleFullscreen] = useFullscreen();
return (
<div>
<h1>Image Gallery</h1>
<div>
{/* Image 1 */}
<img
ref={imageRef}
src="image1.jpg"
alt="Image 1"
onClick={toggleFullscreen}
/>
{/* Image 2 */}
<img
ref={imageRef}
src="image2.jpg"
alt="Image 2"
onClick={toggleFullscreen}
/>
{/* Image 3 */}
<img
ref={imageRef}
src="image3.jpg"
alt="Image 3"
onClick={toggleFullscreen}
/>
</div>
</div>
);
};