Created
June 29, 2021 09:46
-
-
Save nirkaufman/e35f0700fa19ed62d03fc42bbb3575c7 to your computer and use it in GitHub Desktop.
This file contains 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 VideoPlayer from "./VideoPlayer"; | |
const App = () => ( | |
<div> | |
<h1>Declarative Usage</h1> | |
{/* create context for a VideoPlayer */} | |
<VideoPlayer> | |
<VideoPlayer.Player src={"sample.mp4"}/> | |
<VideoPlayer.Play> | |
{/* wrap whatever you want */} | |
<button>My Play</button> | |
</VideoPlayer.Play> | |
<VideoPlayer.Stop> | |
<span>My Stop icon</span> | |
</VideoPlayer.Stop> | |
</VideoPlayer> | |
</div> | |
); | |
export default App; |
This file contains 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 React, { cloneElement, createContext, useContext, useRef, useState } from 'react'; | |
const PlayerContext = createContext(null); | |
// VideoPlayer API | |
export function useVideo () { | |
const ref = useRef(); | |
const [status, setStatus] = useState(); | |
const play = () => { | |
ref.current.play(); | |
setStatus("Playing"); | |
} | |
const stop = () => { | |
ref.current.pause(); | |
setStatus("Stopped"); | |
} | |
return {play, stop, ref, status}; | |
} | |
// Context provide for videoPlayer API | |
const VideoPlayer = ({ children }) => { | |
const playerApi = useVideo(); | |
return ( | |
<PlayerContext.Provider value={playerApi}> | |
{children} | |
</PlayerContext.Provider> | |
); | |
}; | |
// Wrappers for specific video player functionality | |
const Player = ({ src }) => { | |
const {ref} = useContext(PlayerContext); | |
return <video src={src} ref={ref} width={200}/> | |
} | |
const Play = ({ children }) => { | |
const {play} = useContext(PlayerContext); | |
return cloneElement(children, {onClick: play}) | |
} | |
const Stop = ({ children}) => { | |
const {stop} = useContext(PlayerContext); | |
return cloneElement(children, {onClick: stop}) | |
} | |
// Group everything together | |
VideoPlayer.Player = Player; | |
VideoPlayer.Stop = Stop; | |
VideoPlayer.Play = Play; | |
export default VideoPlayer; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment