javascript / intermediate
Snippet
Customizing Ref Interfaces with useImperativeHandle
useImperativeHandle customizes the instance value that is exposed to parent components when using ref. Instead of exposing the entire DOM node, you can provide a limited, specific API of methods.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
import { useImperativeHandle, forwardRef, useRef } from 'react';const FancyEditor = forwardRef((props, ref) => {const inputRef = useRef();useImperativeHandle(ref, () => ({focusAndClear: () => {inputRef.current.focus();inputRef.current.value = '';}}));return <input ref={inputRef} />;});
react
Breakdown
1
useImperativeHandle(ref, () => ({ ... }));
Defines which properties or functions the parent's ref.current will contain.
2
focusAndClear: () => { ... }
Exposes a custom imperative method to the parent component.