Reference a node using createRef() in React 16.3

Share this video with your friends

Send Tweet
Published 4 years ago
Updated 10 months ago

In this lesson, we look at where we came from with refs in React. Starting with the deprecated string ref pattern, callback refs, and then how to use the new createRef() method in React 16.3.

Additional Resources: [refs and the dom](https://reactjs.org/docs/refs-and-the-dom.html https://reactjs.org/blog/2018/03/29/react-v-16-3.html)

Instructor: [00:00] For this demo, I have a simple component that has a field, and two buttons. One to focus and blur the field. In React, most updates are controlled by state and passing props. However, there are some occasions where you actually need the DOM node itself. Focus and blur are a few such cases.

[00:18] React does this with the concept of refs. In my code, I'm using the legacy implementation of refs as a string. This way of utilizing refs has been deprecated for quite some time but React has been nice enough to allow your code and libraries to get by with it and warn you in the console.

[00:33] At some point, React introduced the idea of ref callbacks. Pass a function to the attribute and assign the ref to a property on the class instance, and you've got your node.

[00:46] Ref callbacks is still our recommended way to utilize refs in React, but in my opinion, it's not quite as easy to understand or implement as the string method. In version 16.3, React added a new option called createRef, which make things a little bit more straightforward again.

[01:05] All we have to do now is assign a property in our constructor, or as a class property, to obtain the node, and it'll be found on the current property. Again, if you're going to use refs, React recommends using the ref callback pattern or the new createRef method.