All hooks / Browser APIs

useFullscreen

292 B minified and brotliedSourceMarkdown! Not available in Safari iOS

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.

normal

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

UsesChromeEdgeFirefoxSafariChrome AndroidSafari iOS
Fullscreen APILimited availability71+79+64+16.4+71+✕
  • supported is false where document.fullscreenEnabled isn'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).