Autoplay

    Manipulate the DOM with React refs

    Kent C. DoddsKent C. Dodds

    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.

    reactReact
    ^16.0.0
    Code

    Code

    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
    Transcript

    Transcript

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

    00:24 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.

    00:42 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.

    01:01 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).

    01:20 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.

    01:38 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.

    01:51 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.

    02:10 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.

    Discuss

    Discuss