useFullScreen documentation

The useFullScreen hook is a custom hook for toggling fullscreen mode on and off for a given DOM element. It accounts for various browser implementations of the Fullscreen API.

Type

Hooks

import

import { useFullScreen } from '@pillar-ui/hooks'

Why useFullScreen

The useFullScreen hook simplifies the process of implementing fullscreen mode functionality in a React application. It normalizes different browser implementations and ensures portability of your code.

Installation

You can import the useFullScreen hook into your React component this way:

// With NPM
npm install --dev '@pillar-ui/hooks'

// With YARN
yarn add '@pillar-ui/hooks'

// Uses
import { useFullScreen } from '@pillar-ui/hooks'

Parameters

useFullScreen requires no parameters.

Usage

Here's how to use Fullscreen hook in your functional component:

import { useFullscreen } from '@pillar-ui/hooks'

function MyComponent() {
  const { ref, isFullscreen, enterFullscreen, exitFullscreen } = useFullScreen()

  return (
    <div ref={ref}>
      <button onClick={enterFullscreen}>Go Fullscreen</button>
      {isFullscreen && <button onClick={exitFullscreen}>Exit Fullscreen</button>}
    </div>
  )
}

In this example, a button that triggers fullscreen mode on click, and another button that exits fullscreen mode is shown when the element is currently in fullscreen mode.

Implementation details

The useFullScreen hook uses the Fullscreen API, taking into account variations across different browsers. It uses React's useEffect hook to set up event listeners for relevant Fullscreen events and cleans up these events when the component unmounts.

Additionally, the hook exposes a ref so you can attach a DOM element to be controlled for fullscreen display. Functions to enter fullscreen (enterFullscreen) and exit fullscreen (exitFullscreen) are also provided, as well as a function to toggle the fullscreen state (toggleFullscreen).

TypeScript Support

The useFullScreen hook is written in TypeScript and includes type definitions for its return value.

Troubleshooting

For browsers that don't support the Fullscreen API, this hook will have no effect. Refer to the browser compatibility table on the MDN documentation for the Fullscreen API to ensure the target browsers of your application are supported.

Conclusion

The useFullScreen hook simplifies the process of adding fullscreen functionality in a React application. By normalizing behavior across browsers and handling event subscription and cleanup, it helps in writing clean, efficient code for fullscreen elements.