Created
January 16, 2023 15:42
-
-
Save imbharat420/b3b52af1194a556aa8e1b57cc26ff258 to your computer and use it in GitHub Desktop.
Picture in Picture React Hook
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useState, useEffect } from 'react'; | |
function usePictureInPicture(videoRef) { | |
const [pictureInPictureEnabled, setPictureInPictureEnabled] = useState(false); | |
useEffect(() => { | |
if (!videoRef.current) return; | |
const video = videoRef.current; | |
function onEnterPictureInPicture() { | |
setPictureInPictureEnabled(true); | |
} | |
function onLeavePictureInPicture() { | |
setPictureInPictureEnabled(false); | |
} | |
video.addEventListener('enterpictureinpicture', onEnterPictureInPicture); | |
video.addEventListener('leavepictureinpicture', onLeavePictureInPicture); | |
return () => { | |
video.removeEventListener('enterpictureinpicture', onEnterPictureInPicture); | |
video.removeEventListener('leavepictureinpicture', onLeavePictureInPicture); | |
}; | |
}, [videoRef]); | |
function togglePictureInPicture() { | |
if (!videoRef.current) return; | |
const video = videoRef.current; | |
if (pictureInPictureEnabled) { | |
document.exitPictureInPicture(); | |
} else { | |
video.requestPictureInPicture(); | |
} | |
} | |
return [pictureInPictureEnabled, togglePictureInPicture]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment