Skip to content

Instantly share code, notes, and snippets.

@jrson83
Forked from yannamsellem/use-fullscreen.ts
Created July 5, 2023 01:24
Show Gist options
  • Save jrson83/4af38c6ad5c2a85003dcd22ba63a1801 to your computer and use it in GitHub Desktop.
Save jrson83/4af38c6ad5c2a85003dcd22ba63a1801 to your computer and use it in GitHub Desktop.
FullScreen hook
import { useState, useLayoutEffect } from 'react'
type FullScreenState = boolean
type ToggleFullScreen = () => void
function useFullScreen<E extends HTMLElement>(ref: React.RefObject<E>): [FullScreenState, ToggleFullScreen] {
const [isFullScreen, setFullScreen] = useState(
Boolean(document.fullscreenElement),
)
useLayoutEffect(() => {
function handle() {
setFullScreen(Boolean(document.fullscreenElement))
}
document.addEventListener('fullscreenchange', handle)
return () => document.removeEventListener('fullscreenchange', handle)
}, [setFullScreen])
function toggleFullscreen() {
// eslint-disable-next-line no-unused-expressions
if (!isFullScreen) ref.current?.requestFullscreen()
else document.exitFullscreen()
}
return [isFullScreen, toggleFullscreen]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment