Author avatar

Gaurav Singhal

Find Specific Elements from the DOM in React

Gaurav Singhal

  • Nov 10, 2020
  • 5 Min read
  • 86 Views
  • Nov 10, 2020
  • 5 Min read
  • 86 Views
Web Development
Front End Web Development
Client-side Frameworks
React

Introduction

Web apps contain various HTML elements rendered into the DOM, and based on user interaction, any of the specific DOM elements can be accessed through code. Accessing DOM elements allows you to fetch elements' HTML content, their child elements, or sometimes a specific element's value to process it.

There are various ways to access any of the DOM elements. In this guide, you are going to learn a few approaches that can help you access some specific DOM elements.

Access a DOM Element Using Ref

ref is a common approach to access various DOM elements that work on setting the ref to an element and accessing it based on the name of ref in the component.

Based on the official docs, ref is suitable for:

  • Managing focus, text selection, or media playback
  • Triggering imperative animations
  • Integrating with third-party DOM libraries

With React 16.3.0, the way to create ref is different now than in earlier versions of React. Below is the basic syntax to create the ref.

1
this.ref_name = React.createRef();
jsx

The ref created using createRef() and the variable ref_name can be attached to any DOM element.

To demonstrate, create a simple form with input control and a button. Once a user clicks on the button, the input value should be accessed through the ref.

1
2
3
4
5
6
constructor(props) {
    super(props);
    // Created ref
    this.myInputRef = React.createRef();
    this.getInputValue = this.getInputValue.bind(this);
}
jsx

The ref created gets the constructor's input value, creates the form, and assigns ref to the input element.

1
2
3
4
5
6
7
8
9
10
render() {
    return (
      <>
        <div>
          <input type="text" ref={this.myInputRef} />
          <button onClick={this.getInputValue}>Submit</button>
        </div>
      </>
    );
}
jsx

Along with the <input> control, an additional prop is used, ref, followed by the name of the ref created by you previously. Below is the function from which the value of the input gets accessed.

1
2
3
4
getInputValue() {
    const inputValue = this.myInputRef.current.value;
    console.log(inputValue)
}
jsx

So using the statement this.myInputRef.current.value, the input value can be accessed directly. If you want to access the complete HTML element, you can do it as demonstrated below.

1
const inputElement = this.myInputRef.current;
jsx

One thing to keep in mind is that you cannot use ref with a function because it does not have any instance to the current component.

Access a DOM Element Using ReactDOM.findDOMNode

So far in this guide, you have seen how ref is used to access a DOM element and its value. However, there are other approaches that can also be helpful, and one of them is ReactDOM.findDOMNode().

findDOMNode() is used to find a specific node from the DOM tree and access its various properties, such as its inner HTML, child elements, type of element, etc. In short, it can return all the supported DOM measurements related to the kind of element.

The syntax to use findDOMNode() in React is as follows:

1
ReactDOM.findDOMNode(component_name)
jsx

Along with findDOMNode(), you can pass the name of the component or element you want to access from the DOM. To illustrate the concept, let's create an example that has input control and a button. With a click on the button, input control should be focused.

Create the ref for input control is as demonstrated below.

1
2
3
4
5
6
constructor(props) {
    super(props);
    this.myInputRef = React.createRef();
    this.state = {};
    this.onFocusInput = this.onFocusInput.bind(this);
}
jsx

After creating the ref, create one input control and add additional props called ref. Once the user clicks the button, the input will be accessed from findDOMNode().

1
2
3
4
5
6
7
8
9
10
render() {
    return (
      <>
        <div>
          <input type="text" ref={this.myInputRef} />
          <button onClick={this.onFocusInput}>FOCUS</button>
        </div>
      </>
    );
}
jsx

Once the user clicks on the focus button, it goes to the function onFocusInput and tries to find the DOM element based on the ref and then uses the focus() method to focus the selected input control.

1
2
3
onFocusInput() {
    ReactDOM.findDOMNode(this.myInputRef.current).focus();
}
jsx

Observe that as soon as you click on the button, input control is auto-focused, which is done by using findDOMNode() along with the focus() method.

Note : As per the official docs, findDOMNode() only works on mounted components (that is, components that are placed in the DOM.) If you try to call on an element that has yet not mounted (like calling findDOMNode() in render() on a component that has yet to be created), an exception will get thrown. findDOMNode cannot be used on function components.

Conclusion

Accessing DOM elements and their current values is a top concern when working in web apps. There should be a suitable approach that makes your DOM manipulation way easier than ever before.

All DOM elements in React can be accessed in multiple ways, such as ref or findDOMNode(), so choose your implementation approach wisely. I hope this guide helped you understand how to access DOM elements.

0