Skip to content

Instantly share code, notes, and snippets.

@nirkaufman
Created June 29, 2021 09:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nirkaufman/e35f0700fa19ed62d03fc42bbb3575c7 to your computer and use it in GitHub Desktop.
Save nirkaufman/e35f0700fa19ed62d03fc42bbb3575c7 to your computer and use it in GitHub Desktop.
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;
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