・This pattern enables you to utilize specific methods from a parent component by exposing it to the parent component through a ref with useimperativeHandle.
import { useRef, useImperativeHandle } from "react";
function Input({ ref, ...rest }) {
const childRef = useRef();
useImperativeHandle(ref, () => ({
focusInner: () => {
childRef.current.focus();
},
}));
return <input ref={localRef} {...rest} />;
}
function App() {
const inputRef = useRef();
const handleFocus = () => {
inputRef.current.focusInner()
};
return (
<div>
<Input ref={inputRef} placeholder="Focus me" />
<button onClick={handleFocus}>Focus Input</button>
</div>
);
}
export default App;
Top comments (0)