How to Implement Forwarding Refs in React
Ref forwarding is a technique in React that allows components to take
a ref they receive and pass it further down to a child
component. This article provides a clear, step-by-step guide on how to
implement forwarding refs in React using the
React.forwardRef API, explaining both the syntax and
practical use cases like accessing DOM nodes of child components.
In React, standard props do not include ref because
React treats it as a special attribute, similar to key. To
pass a ref through a component to one of its DOM elements,
you must use the React.forwardRef utility function.
Step 1: Define the Child Component with React.forwardRef
To implement ref forwarding, wrap your functional component with
React.forwardRef. This function accepts a rendering
function as its argument. This rendering function receives the
component’s props as the first argument and the
ref as the second argument.
import React from 'react';
const CustomInput = React.forwardRef((props, ref) => {
return (
<input ref={ref} type="text" className="custom-input" {...props} />
);
});
CustomInput.displayName = 'CustomInput';
export default CustomInput;In this example, the CustomInput component forwards the
received ref directly to the native HTML
<input> element. Setting the displayName
property is a best practice to ensure the component is named correctly
in React DevTools.
Step 2: Pass the Ref from the Parent Component
Once the child component is configured to forward refs, you can
create a ref in the parent component using the useRef hook
and pass it to the child component as a ref attribute.
import React, { useRef } from 'react';
import CustomInput from './CustomInput';
function ParentComponent() {
const inputRef = useRef(null);
const focusInput = () => {
if (inputRef.current) {
inputRef.current.focus();
}
};
return (
<div>
<CustomInput ref={inputRef} placeholder="Type here..." />
<button onClick={focusInput}>Focus Input</button>
</div>
);
}
export default ParentComponent;When to Use Ref Forwarding
- Managing Focus, Text Selection, or Media Playback: Accessing a child element’s DOM node directly to trigger focus or animations.
- Reusable Component Libraries: Creating highly reusable leaf components (like buttons, inputs, and text fields) that need their DOM nodes exposed to parent components for DOM layout measurements.
- Higher-Order Components (HOCs): Passing refs through HOC wrapper components to the wrapped component.