javascript / intermediate
Snippet
Exposing Imperative API with useImperativeHandle
When using 'forwardRef', you might want to expose custom methods to the parent rather than the raw DOM node. 'useImperativeHandle' lets you define exactly which properties and functions the parent component can access through the ref.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import { useImperativeHandle, forwardRef, useRef } from 'react';const VideoPlayer = forwardRef((props, ref) => {const videoRef = useRef();useImperativeHandle(ref, () => ({play: () => videoRef.current.play(),stop: () => {videoRef.current.pause();videoRef.current.currentTime = 0;}}));return <video ref={videoRef} src={props.src} />;});
react
Breakdown
1
useImperativeHandle(ref, () => ({ ... }))
Defines the object that will be assigned to the 'current' property of the parent's ref.
2
play: () => videoRef.current.play()
Exposes a specific 'play' function while keeping the internal video element encapsulated.