How To Get An Element By ID In React

How To Get An Element By ID In React

To get an element by ID in React you can choose to use useRef hook or document.getElementById() method. Follow along with this article to see our detailed instructions.

The ‘useRef hook in React 

The useRef hook is a function that returns an object with the current property initialized via the passed parameter. This returned object can be mutated and persist for the component’s lifetime.

Code:

const refContainer = useRef(initialValue);

There are 2 main reasons we would use useRef:

  • Accessing DOM nodes or React elements
  • Storing a mutable variable.

In React, a ref is an attribute of a tag or element representing itself. ref allows us to access the mounted DOM node or React element. In vanilla Javascript, we work with DOM elements by calling document.getElementById(). With ref in React, we don’t have to. The ref attribute will refer to the same element to be used. The ref takes a variable or a function. If it is a function, then this function will be run when the element is mounted.

ref

A ref is created when the component is mounted. ref is assigned to an element. If you want to pass the ref through the component, use forwardRef.

The ref can be used to access the DOM node or React element and store mutable variables without re-rendering the component.

Some methods to get an element by ID in React

Use document.getElementById() method

The example below will show you how it works. document.getElementById() in JavaScript is a method of DOM object, which works to get an element from the DOM through the value of that element’s id attribute.

Code:

export default function App() {
    return (
        <div>
            <h1 id="title">LearnShareIT</h1>
            <button
              onClick={() => {
                  var element = document.getElementById("title");
                  console.log(element);
                  element.innerHTML = "#title";
              }}
              >
              	Show ID
            </button>
        </div>
    );
}

Output:

<h1 id="title">#title</h1>

When you use this method, getting the element by ID will be possible. Specifically, here is the <h1> tag with the id "title". The following way will do a more recommended way to follow the article.

Use useRef hook

In this way, we will use the useRef hook to create a ref for the <h1> tag to be able to point to it. Here are some valid use cases for a ref:

  • When managing focus, text selection, or media playbacks.
  • When managing animations.
  • When integrating with a third-party library.

Code:

import { useRef, useEffect } from 'react';
 
export default function App() {
    const ref = useRef(null);
    const element = ref.current;
  
    return (
        <div>
            <h1 ref={ref} id="title">
              LearnShareIT
            </h1>
            <button onClick={() => {
                console.log(element);
            }}>
              	Show element
        	</button>
        </div>
    );
}

Output:

<h1 id="title">#title</h1>

The above code is an example of its usage in practice. When you press the ‘Show element’ button, the program will print the <h1> tag we need to get to the console. I hope these methods are helpful for you.

Summary

To summarize, there are many ways to get an element by ID in React. We know some easy ways like using document.getElementById() method or useRef hook in Javascript to do it. Let’s try these two methods.

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *