Skip to content

React.forwardRef

React.forwardRef is a technique provided by React for passing a ref down to a child component. This is especially useful when you need to access a DOM element directly within a child component or when you're working with higher-order components (HOCs) and you need the ref to pass through the HOC to a child component.

Normally, ref is not a prop that gets passed down to child components. If you add a ref to an element, React handles it differently from props like className or id, and it doesn't make it accessible to the child component. This special handling is designed for performance and abstraction reasons. However, there are cases when you need to explicitly pass down a ref to a child component. That's where React.forwardRef comes in.

Basic Usage

React.forwardRef creates a React component that forwards the ref attribute it receives to another component below in the tree. This can be particularly useful for highly reusable component libraries.

Here’s a simplified signature of React.forwardRef:

jsx
const ComponentWithRef = React.forwardRef((props, ref) => {
  // You can now use the ref parameter inside your component.
});
  • props: An object containing the props passed to the component.
  • ref: The ref passed to the component.

Example

Consider a FancyButton component that you want the parent component to be able to reference:

jsx
const FancyButton = React.forwardRef((props, ref) => (
  <button ref={ref} className='FancyButton'>
    {props.children}
  </button>
));

// You can now get a ref directly to the DOM button:
const ref = React.createRef();
<FancyButton ref={ref}>Click me!</FancyButton>;

In this example, the FancyButton uses React.forwardRef to obtain the ref passed to it, and then forwards it to the <button> DOM element. As a result, the parent component that renders FancyButton can interact with the DOM button directly using the ref.

When to Use React.forwardRef

  • Accessing DOM elements directly: When you need to manage focus, select text, or media playback.
  • Creating reusable component libraries: When making a component library that wraps and hides implementation details of components, forwardRef can be used to allow the library users to access the underlying DOM elements.
  • Higher-order components (HOCs): To pass a ref through a HOC to a child component.

React.forwardRef is a powerful tool, but it's recommended to use it sparingly as it breaks the usual data flow patterns in React applications and can make components less reusable.

alt textalt text

Contributors

No contributors

Changelog

No recent changes