What is Forwarding Refs in React?
Ref forwarding is a technique in React that allows a component to
take a ref it receives from a parent and pass (or
“forward”) it further down to one of its child components. This article
provides a clear overview of why ref forwarding is necessary, how to
implement it using the React.forwardRef API, and the most
common scenarios where this pattern is highly beneficial.
The Problem with Standard Refs and Custom Components
In React, references (refs) provide a way to access the underlying DOM nodes or React element instances directly. Normally, you might use a ref to manage focus, select text, or trigger animations.
However, you cannot pass a ref attribute to a custom
function component the same way you pass standard props. Because
function components do not have instances, React treats the
ref attribute specially—similar to the key
prop—and does not pass it down to the component’s argument list. If you
attempt to access props.ref, it will return
undefined.
How Ref Forwarding Works
To solve this issue, React provides the React.forwardRef
API. This function wraps a component, intercepting the ref
passed to it, and exposes it as a second argument to the component’s
render function.
Here is how you define a component with ref forwarding:
import React, { forwardRef } from 'react';
const CustomInput = forwardRef((props, ref) => {
return <input ref={ref} {...props} type="text" />;
});
export default CustomInput;In this example, CustomInput is a React component that
forwards its ref directly to the native HTML <input>
element inside it.
Consuming a Forwarded Ref
Once you have created a component that forwards refs, parent components can interact with the inner DOM node as if they were targeting it directly:
import React, { useRef } from 'react';
import CustomInput from './CustomInput';
function ParentComponent() {
const inputRef = useRef(null);
const focusInput = () => {
// Directly focus the input element inside CustomInput
inputRef.current.focus();
};
return (
<div>
<CustomInput ref={inputRef} placeholder="Type here..." />
<button onClick={focusInput}>Focus Input</button>
</div>
);
}When the ParentComponent mounts,
inputRef.current points to the native
<input> DOM node inside CustomInput.
When to Use Ref Forwarding
Ref forwarding is highly useful in specific scenarios:
- Accessing DOM Nodes of Reusable Leaf Components: Components representing highly reusable UI elements like buttons, inputs, and text fields often need their DOM nodes accessed by parents to manage focus, selection, or sizing.
- Higher-Order Components (HOCs): If you wrap a component in a Higher-Order Component to add styles or state, you should forward the ref so that parents can still access the underlying wrapped component.
- Integrating with Third-Party DOM Libraries: When using non-React libraries that require direct DOM access, forwarding the ref allows you to hook those libraries into specific elements within your React component tree.