forwardRef: Exposing DOM Refs to Parents
Learn how forwardRef lets parent components access a child's DOM node or component instance.
What Refs Are and the Default Limitation
A ref is a way to hold a reference to a DOM node or component instance that persists across renders without triggering re-renders. You attach one with the ref attribute, and React fills in its current property after committing to the DOM.
The catch is that you cannot attach a ref to a function component the way you would a div. By default a parent has no path to reach the DOM node living inside a child component, because refs are not passed down like ordinary props.
forwardRef Wraps a Component
React.forwardRef lets a component receive a ref from its parent and forward it onward to one of its own elements. It wraps your component function and changes the function signature so that ref arrives as a second argument alongside props.
This is the official escape hatch for exposing an inner DOM node to a calling component, turning an otherwise opaque child into one whose element a parent can directly reference.
All lessons in this course
- forwardRef: Exposing DOM Refs to Parents
- useImperativeHandle: Custom Instance Values
- Building an Imperative Component API
- When to Use Imperative vs Declarative APIs