Skip to content

Instantly share code, notes, and snippets.

@Debajyati
Forked from louis-young/index.tsx
Created June 5, 2025 07:26
Show Gist options
  • Save Debajyati/a88ab132528df720da492e7dea003581 to your computer and use it in GitHub Desktop.
Save Debajyati/a88ab132528df720da492e7dea003581 to your computer and use it in GitHub Desktop.
useImperativeHandle with TypeScript and function components
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