-
-
Save Debajyati/a88ab132528df720da492e7dea003581 to your computer and use it in GitHub Desktop.
useImperativeHandle with TypeScript and function components
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 { forwardRef, useImperativeHandle, useRef } from "react"; | |
export interface VideoProps { | |
source: string; | |
} | |
export interface VideoRef { | |
play: () => void; | |
pause: () => void; | |
} | |
export const Video = forwardRef<VideoRef, VideoProps>(({ source }, ref) => { | |
const videoRef = useRef<HTMLVideoElement>(null); | |
useImperativeHandle(ref, () => { | |
return { | |
play: () => { | |
videoRef.current?.play(); | |
}, | |
pause: () => { | |
videoRef.current?.pause(); | |
} | |
}; | |
}); | |
return ( | |
<video controls width="250" ref={videoRef}> | |
<source id="mp4" src={source} type="video/mp4" /> | |
</video> | |
); | |
}); | |
export const Application = () => { | |
const videoRef = useRef<VideoRef>(null); | |
return ( | |
<div className="App"> | |
<button onClick={() => videoRef.current?.play()}>Play from parent</button> | |
<button onClick={() => videoRef.current?.pause()}> | |
Pause from parent | |
</button> | |
<Video | |
ref={videoRef} | |
source="http://media.w3.org/2010/05/sintel/trailer.mp4" | |
/> | |
</div> | |
); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment