useFullscreen
Enter and exit fullscreen mode for a given element or the entire page.
Installation
Props
Prop | Type | Default | Description |
---|---|---|---|
ref | RefObject<HTMLElement> | null | null | The ref of the element to enter/exit fullscreen. If null, uses the document. |
Data
Prop | Type | Description |
---|---|---|
isFullscreen | boolean | Whether the element (or page) is in fullscreen. |
enter | () => void | Function to enter fullscreen mode. |
exit | () => void | Function to exit fullscreen mode. |
Notes
- The hook is cross-browser compatible and uses the appropriate vendor-prefixed Fullscreen API methods.
- Only works in the browser (client-side). Ensure you use it in a client component.
- If the Fullscreen API is not available, the functions will be no-ops.
Key Features & Details
Cross-Browser Support
- The hook uses the appropriate vendor-prefixed Fullscreen API methods for compatibility with all major browsers.
- Listeners for fullscreen changes are also vendor-prefixed.
Ref Behavior
- If a
ref
is provided, the hook will enter/exit fullscreen for that element. - If
null
is passed, the hook will use the entire document (document.documentElement
).
State Updates & Event Handling
- The hook tracks whether the referenced element (or the page) is currently in fullscreen.
- Listens for fullscreen change events and updates state accordingly.
- The state is updated immediately on mount and whenever fullscreen changes.
Returned Values
- Returns a tuple:
[isFullscreen, enter, exit]
. isFullscreen
istrue
if the element (or page) is in fullscreen.enter
andexit
are functions to enter/exit fullscreen mode.
Cleanup
- All event listeners are removed automatically when the component unmounts.
Caveats & Best Practices
- Only works in the browser (client-side). On the server, the functions are no-ops.
- If the Fullscreen API is not available, the functions will be no-ops.
- The element must be in the DOM and visible to enter fullscreen.
- Some browsers may block fullscreen requests unless triggered by a user gesture.
Examples
Fullscreen for the Whole Page
const [isFullscreen, enter, exit] = useFullscreen();
Toggle Fullscreen
const boxRef = useRef<HTMLDivElement>(null);
const [isFullscreen, enter, exit] = useFullscreen(boxRef);
const toggle = () => {
isFullscreen ? exit() : enter();
};