Use forwardRef() in React 16.3

Share this video with your friends

Social Share Links

Send Tweet

In this lesson, we look at the new forwardRef() method in React 16.3, and how it helps us forward a ref through a Higher-order component to reference an inner DOM node.

Additional Resources: https://reactjs.org/docs/forwarding-refs.html

Andrew Del Prete: [00:00] I have a presentational component called Box and a higher-order component, which embellishes the Box a bit by providing a click and hover handler. These handlers simply alert or log out the text in the Box.

[00:13] For this demo, I like to get the X and Y coordinates of the Box by clicking this button. Right now, it doesn't actually do anything. To do this, I'll need to retrieve the actual node of the Box in the DOM to find the offset left and offset top.

[00:26] Since BoxAdvanced is a higher-order component, I can't just add a ref to it. The ref would reference the component instance itself and not the DOM node of the div we're trying to fetch.

[00:37] React 16.3 comes to the rescue by helping us solve this issue by using something called the forwardRef function. First, I'll need to create a ref. To do this, I'll use the new createRef method.

[00:48] To learn more about createRef, check out my other video covering it. TLDR, it's a new way to create and assign refs. Next, I'll go ahead and assign the ref to BoxAdvanced, so I can use it in just a second.

[00:59] I'll need to go ahead and modify the with Advanced higher-order component, so it knows what to do with the ref we're passing in. Remember, right now, it's going to reference the higher-order component itself, which we don't want.

[01:10] This ref is a special attribute and now a normal property, React 16.3 differentiates between the two by giving us a second argument to work with when we're using forwardRef, which is also a higher-order component of sorts and expects a component with props and a ref.

[01:26] I'm going to take that ref argument and pass it as a property to the component being embellished by the higher-order component, which is Box in this case. The property can really be called anything you want.

[01:37] I'm using forwardedRef. They use it in the docs, and it makes sense to me. Now, I can pull forwardedRef into Box and assign it to the ref attribute. Finally, I need to get the coordinates in my app component and open and alert when clicking the button.

[02:01] It looks like it works. I hope this helps you understand how to forward a ref through a higher-order component to reference an inner Dom node.