Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


    Reference a node using createRef() in React 16.3

    Andrew Del PreteAndrew Del Prete

    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)



    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson




    Instructor: 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.

    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.

    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.

    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.

    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.