React - Forwarding Ref

About

A forwarding ref is when you pass a ref to a component as attribute in order to get a ref in one of its child component.

By default:

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

Example

  • A component where we have added a ref as prop
const FancyButton = React.forwardRef((props, ref) => (
  <button ref={ref} className="FancyButton">
    {props.children}
  </button>
));
  • Create a ref and pass it to the button component in order to get access to the child button element
const ref = React.createRef();
const ClickMe = <FancyButton ref={ref}>Click me!</FancyButton>;
console.log("The ref is null before rendering");
console.log(ref);
  • Rendering
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";
  • The standard mandatory “root” DOM node (placeholder for React DOM manipulation)
<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'

Documentation / Reference


Powered by ComboStrap