All hooks / Browser APIs
useFullscreen
Puts an element into fullscreen and tracks whether it is, including when the user leaves with Esc or a browser control.
Returns a callback ref for the element and controls. enter must be called from a user action (click, keypress); browsers refuse otherwise.
Import
import { useFullscreen } from '@vincent.ri/react-tils'
// or only this hook
import { useFullscreen } from '@vincent.ri/react-tils/useFullscreen'Usage
const [ref, fullscreen] = useFullscreen<HTMLDivElement>()
return (
<div ref={ref}>
<Slides />
{fullscreen.supported && (
<button onClick={fullscreen.toggle}>{fullscreen.active ? 'Exit' : 'Fullscreen'}</button>
)}
</div>
)Live demo
Esc also exits.
When to use it
A fullscreen button for a video player, image viewer, slideshow, game, or map.
When not to
You only need a large layout; use CSS (position: fixed; inset: 0). On iPhone, only <video> can go fullscreen, through the video's own controls, so check supported before showing the button.
API
function useFullscreen<T extends Element = HTMLElement>(): [(element: T | null) => void, Fullscreen]Returns [ref, { supported, active, enter, exit, toggle }].
Types
export type Fullscreen = {
/** `false` where elements can't go fullscreen (e.g. iPhone Safari), on the server, and during hydration. */
supported: boolean;
/** `true` while this element is fullscreen. */
active: boolean;
/** Make the element fullscreen. Resolves `false` if the browser refuses. Call from a user action. */
enter: () => Promise<boolean>;
/** Leave fullscreen if this element is fullscreen. */
exit: () => Promise<void>;
toggle: () => Promise<void>;
};Browser support
| Uses | Chrome | Edge | Firefox | Safari | Chrome Android | Safari iOS |
|---|---|---|---|---|---|---|
| Fullscreen APILimited availability | 71+ | 79+ | 64+ | 16.4+ | 71+ | ✕ |
supportedisfalsewheredocument.fullscreenEnabledisn't true, including on iPhone, where Safari allows fullscreen only for<video>.
First version with support, from MDN's compatibility data (web-features 3.42.0, @mdn/browser-compat-data 8.1.5).