How to Use The Forwarded Ref in React
Dealing with refs has evolved a lot since React’s beginnings. React has gone from using a ref
property on the component class and passing a string to the ref property of an element, to using ref
callbacks that receive the DOM reference as an argument, to ref
objects that expose the DOM reference in the on the current
property of the ref
object. Use of the ref
object has also evolved, created with createRef
and now more commonly used with the useRef
hook.
As a component author, exposing the ref of an underlying element has also evolved. Originally it had to be exposed using some arbitrary prop, though conventionally named innerRef
, and mapping it to the ref of the underlying element. Though this worked, React recently added a better way to expose the ref
of an underlying element. Using React.forwardRef
we can pass a function component and now have the ref forwarded to the component as the second argument after the props argument. Then it is as simple as mapping that ref to the underlying element, like this:
const Div = React.forwardRef((props,ref)=>{
return <div ref={ref} {...props}/>
});
And now we can use our component as if it was any other React element:
const App = () =>{
const divRef = React.useRef();return <Div ref={divRef}>{...}</Div>
}