When and how you use React refs

React refs are a feature of React that you should never use until you absolutely have to. They give you access directly to the DOM, which is something you're not supposed to really do in React.

You see, refs are what you consider an escape hatch. In React you're always supposed to render new things by changing props or state and letting the React engine re render your thing. But with refs, you're able to go right into the DOM and have direct, imperative access to whatever you're rendering so that you can for instance start videos, focus on text fields or sometimes interact with third party libraries like D3 or J Quarry and stuff.

You can think of your React component as a container that contains a DOM element, and the DOM element is the part that's actually being rendered in your browser because the browser doesn't understand what React components are. The React component has a bunch of logic, blah, blah, blah, and you can use refs to get a reference directly to a DOM note so that you can manipulate it. It's probably best if we look at what this looks like in code, then let's make a small video component that we can press play on.

I've prepared a simple video React component that renders a video HTML5 element and one of our button components that just says play on it, and has an enclave callback. To get our video to actually play, we're going to say video ref is React.createRef. We add it as a ref prof to our video element in the play function. We then say this.videoref.current.play. There you go, I press play here and this starts playing.

Obviously in a real world scenario you would download a pre made video component for React because doing all of this stuff is kind of tedious and annoying. It's a good example of how Reacts work and of something that you can't do directly without the clarity of rendering API.

And that's how you use React refs. You create a ref to your element and then you use normal DOM APIs and JavaScript stuff to control that DOM note. It's pretty simple.

Know someone who wants to learn React and its whole ecosystem? Share 👇


Cheers,
~Swizec