Careeroza
useImperativeHandle
Expose Methods to a Parent
const FancyInput = forwardRef(function FancyInput(props, ref) {
const inputRef = useRef(null);
useImperativeHandle(ref, () => ({
focus: () => inputRef.current.focus(),
clear: () => { inputRef.current.value = ''; },
}));
return <input ref={inputRef} />;
});
function Parent() {
const ref = useRef();
return (
<>
<FancyInput ref={ref} />
<button onClick={() => ref.current.clear()}>Clear</button>
</>
);
}Note: Rarely needed. Prefer props; use this for things like focus(), scrollTo(), play().