Blog>
Snippets

Custom Input Component with useImperativeHandle

Expose a focus method in a child input component to the parent by using useImperativeHandle and forwardRef, allowing the parent to focus the input when needed.
import React, { useRef, useImperativeHandle, forwardRef } from 'react';
Import necessary hooks and functions from React.
const CustomInput = forwardRef((props, ref) => {
  const inputRef = useRef();
  useImperativeHandle(ref, () => ({
    focus: () => {
      inputRef.current.focus();
    }
  }));

  return <input ref={inputRef} {...props} />;
});
Define CustomInput component that uses useRef to reference the input element and useImperativeHandle to expose a focus method to the parent component.
const ParentComponent = () => {
  const inputRef = useRef();

  const focusInput = () => {
    inputRef.current.focus();
  };

  return (
    <div>
      <CustomInput ref={inputRef} />
      <button onClick={focusInput}>Focus the input</button>
    </div>
  );
};
Create ParentComponent that contains CustomInput and a button that when clicked, calls the focus method on the CustomInput.
export default ParentComponent;
Export ParentComponent so it can be used in other parts of the application.