How to forward refs in React with forwardRef

· Category: React

Short answer

forwardRef lets a component pass a ref it receives to one of its child elements, enabling parent components to directly access DOM nodes or child instances.

Steps

  1. Wrap your component with React.forwardRef((props, ref) => ...).
  2. Assign the ref to the desired child element.
  3. Use the ref from the parent as usual.

Example

const FancyInput = React.forwardRef((props, ref) => (
  <input ref={ref} className="fancy" {...props} />
));

function Parent() {
  const inputRef = useRef(null);
  useEffect(() => { inputRef.current.focus(); }, []);
  return <FancyInput ref={inputRef} />;
}

Tips

  • In React 19+, forwardRef is being deprecated in favor of passing ref as a normal prop.
  • Use useImperativeHandle with forwardRef to expose a limited API instead of the full DOM node.