useImperativeHandle(ref, createHandle, [dependencies])
useImperativeHandle(ref, () => ({
focus: () => inputRef.current.focus(),
}));
import React, { render, useRef, useImperativeHandle } from 'react';
const InputWithFocus = React.forwardRef((props, ref) => {
const inputRef = useRef();
useImperativeHandle(ref, () => ({
focus: () => inputRef.current.focus(),
}));
return <input ref={inputRef} type="text" />;
});
function ParentComponent() {
const inputRef = React.useRef();
return (
<div>
<InputWithFocus ref={inputRef} />
<button onClick={() => inputRef.current.focus()}>
Focus Input
</button>
</div>
);
}
render(<ParentComponent />)
body {
padding: 16px;
font-size: 24px;
}
h1 {
font-size: 32px;
}
import React, { render, useRef, useImperativeHandle } from 'react';
const Modal = React.forwardRef((props, ref) => {
const [isOpen, setIsOpen] = React.useState(false);
React.useImperativeHandle(ref, () => ({
open: () => setIsOpen(true),
close: () => setIsOpen(false),
toggle: () => setIsOpen((prev) => !prev),
}));
return isOpen ? (
<div style={{
border: "1px solid black",
padding: "1rem"
}}>
<h2>Modal</h2>
<button onClick={() => setIsOpen(false)}>
Close
</button>
</div>
) : null;
});
body {
padding: 16px;
font-size: 24px;
}
h1 {
font-size: 32px;
}