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:
- 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
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'
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.
- In jsx:
let forwardRefReactElement = <MyForwardRef ...props/>
- In Pure React API Javascript:
let forwardRefReactElement = React.createElement(MyForwardRef, props);