EN
React - how to forward reference to component
3
points
In this article, we would like to show you how to forward reference to a component in React.
The ref
property is reserved by React, so we are not able to pass it inside the component through the props. To solve the problem we can use forwardRef()
function, which wraps the component passing as the second argument ref
property.
Practical example:
// ONLINE-RUNNER:browser;
// import React from 'react';
// import ReactDOM from 'react-dom';
const MyButton = React.forwardRef(({name}, ref) => {
return (
<button ref={ref}>{name}</button>
);
});
const App = () => {
const buttonRef = React.useRef(); // buttonRef.current property is <button> DOM element reference
return (
<div>
<MyButton ref={buttonRef} name="Click me!" />
</div>
);
};
const root = document.querySelector('#root');
ReactDOM.render(<App />, root);
In the above example:
useRef
- creates reference object,buttonRef
- storesMyButton
component reference (in our case it is reference to<button>
DOM element),forwardRef
- forwards reference to the wrapped component.