DEV Community

Cover image for ReactJS Hook Pattern ~ImperativeHandle with useImperativeHandle~
Ogasawara Kakeru
Ogasawara Kakeru

Posted on

ReactJS Hook Pattern ~ImperativeHandle with useImperativeHandle~

・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;


Enter fullscreen mode Exit fullscreen mode

Top comments (0)