How to Access a DOM Element in React: 2 Ways

Sometimes you need to grab a DOM element like an input directly in order to bring it into focus.

You can call it in a function using JavaScript’s “document.getElementById()”, but that’s not a very React way of doing things.

Instead, there are 2 main ways of accessing a DOM element by creating a `ref` on an element.

Option 1: Create a Ref

A `ref`, as you may have guessed, is a reference to a DOM object.

Once you assign a ref to an element, you can access it anywhere in that component’s functions.

Here’s an example of how you’d create and use a ref:

There are a few key points to this:

  1. You must define your ref in the constructor of a class component. (e.g. “ this.inputRef = React.createRef()”)
  2. You must then add that ref name to the element you’d like to interact with. (e.g. “ref={this.inputRef}”)
  3. Finally, you can access that ref in any function by calling the current property on its name (e.g. “this.inputRef.current”), followed by whatever you’d like to do with it (e.g. “.value”, “.focus()”, etc.).

Option 2: Use the createRef Hook

You can also create refs using hooks, although the process is almost identical.

I don’t believe either method is superior to the other, so pick the option you like most.

Here’s what our example looks like if you refactored it into a functional component using hooks:

Here’s how you create a ref with createRef:

  1. While there’s no constructor in a functional component, you still need to define your ref before using it. Near the top of the function, define it. (e.g. “const inputRef = React.useRef()”)
  2. Again, add a “ref” property to the DOM element in your JSX that you’re interested in. (e.g. “ref={inputRef}”).
  3. Again, you can access it by calling its name, followed by its current property. (e.g. “inputRef.current”), which can be followed by other properties (e.g. “.value”, “.focus()”, etc.).

It’s very similar, but provides an option if you’re trying to add a ref to an existing functional component.