Become a member
to unlock all features

Level Up!

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


    Manipulate the DOM with React refs


    Often you'll find there's a jQuery plugin or JavaScript library which needs access to DOM nodes to work in your application. Other times you need access to the DOM node directly to get the value of form fields or for other reasons. In this lesson we'll learn how to do this using React's ref prop.



    Become a Member to view code

    You must be a Pro 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
    orLog In




    We'll start by making a class called tilt that extends React.component. That'll have a render. We'll return a div, another div, yet another div, and this one is just going to spread this.props. On our root div, we'll have a classname, tiltRoot.

    Then we'll have a classname on this one called tiltChild. Then we'll go ahead and use that. We'll put tilt inside of here, put this inside of tilt, and then we'll add a div inside of here. That div will have a classname of totallyCentered.

    Next, we'll go ahead and add a ref prop. We'll say node is this.rootNode equals that node. Then in our componentDidMount, we can console.log(this.rootNode). Pop over developer tools, and we'll see we get that rootNode.

    Now, we can use this node with vanilla-tilt. Let's go ahead and bring in the vanilla-tilt library. I'll just paste a script here for that. Then we can use the vanilla-tilt library with the vanilla-tilt global. We'll say .init(this.rootNode).

    Then we can pass some options. We'll say max is 25, speed is 400, glare true, and max glare 05. We'll get rid of that console.log. Now, if we hover over it, we get that vanilla tilt.

    In review, to be able to manipulate the DOM directly, you need to pass a ref onto your element that you're rendering. When you pass a ref to an element like this, we're going to get a reference to the DOM node.

    If we were to pass a ref to tilt, then what we're going to get is a reference to the instance. It would be the same thing as this. We'll get this as a reference in our ref on a composite component, but because we're putting it on the div, we get access to the DOM node.

    We assign that to this.rootNode, and once the component's mounted, we have that node. We say, "Hey, vanilla-tilt, I want you to initialize on this node with these options." That gives us our really cool effect here.