Table of Contents

React - Forwarding Ref

About

The forwardRef function wraps a element to add to the props a ref that is generated by React.

This ref is called a forwarding ref because you pass it along to use it in one of its child components in order to get a ref on them.

By default:

You need to make the component forward ref aware. See addcreate

Example

const FancyButton = React.forwardRef((props, ref) => (
  <button ref={ref} className="FancyButton">
    {props.children}
  </button>
));
const ref = React.createRef();
const ClickMe = <FancyButton ref={ref}>Click me!</FancyButton>;
console.log("The ref is null before rendering");
console.log(ref);
ReactDOM.render(
  ClickMe,
  document.getElementById('root')
);
console.log("The ref is no more null after rendering");
console.log(ref);

console.log("And you can use it to change whatever you want");
ref.current.innerHTML="Text modified by a Forward Ref";
<div id="root"></div>

Management

Add / Create

To add a ref as attribute, you encapsulate your component with the React.forwardRef function

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

Set Name

In dev tool, to get a display name, set displayName

FancyButton.displayName = 'FancyButton'

How to create from a forwardRef a React element

A forward ref is just an element wrapper that adds automatically a ref.

You can therefore create a React Element the same way as any other element.

let forwardRefReactElement = <MyForwardRef ...props/>
let forwardRefReactElement =  React.createElement(MyForwardRef, props);

Documentation / Reference