React - Forwarding Ref

1 - 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:
  • Regular function or class components don’t receive the ref argument,
  • ref is not available in props either.

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

3 - 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>

4 - Management

4.1 - 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>
));

4.2 - Set Name

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


FancyButton.displayName = 'FancyButton'

5 - Documentation / Reference


Data Science
Data Analysis
Statistics
Data Science
Linear Algebra Mathematics
Trigonometry

Powered by ComboStrap