Ref a DOM Element

In this lesson, we'll learn how to interact with DOM nodes in React.

Why interact with the DOM?

Sometimes you need to interact with your DOM nodes in React. The ref attribute gives you access to a node in your elements. That is usually an anti pattern in React, because you should use its declarative way of doing things and its unidirectional data flow. We learned about it when we introduced the first search input field, but there are certain cases where you need access to the DOM node.

The official documentation mentions three:

  • to use the DOM API to manage focus, media playback etc
  • to invoke imperative DOM node animations
  • to integrate with a third-party library that needs the DOM node (e.g. D3.js)

Referring to the DOM in the Search component

We’ll use the Search component as an example. When the application renders for the first time, the input field should be focused. This is one case where we need access to the DOM API. The ref attribute can be used in both functional stateless components and ES6 class components. In this example, we need a lifecycle method, so the approach is showcased using the ref attribute with an ES6 class component.

The initial step is to refactor the functional stateless component to an ES6 class component.

Get hands-on with 1400+ tech skills courses.