Get an element by ID in React

Get an element by ID in React

In this quick example, we will see how to get an element by ID in React using useRef and useEffect.

In plain JavaScript, we can use APIs such as document.getElementById to get elements by ID. However if using React, it's recommended to use React APIs such as useRef, let's learn how to get a DOM element by ID.

First import the hooks that we'll be using:

import * as React from 'react';
import { useRef, useEffect } from 'react';
import './style.css';

export default function App() {
  return (
    <div>
      <h1>Hello StackBlitz!</h1>
      <p>Start editing to see some magic happen :)</p>
    </div>
  );
}

Next, define a reference and set it on the ref prop of the element you want to access:

import * as React from 'react';
import { useRef, useEffect } from 'react';
import './style.css';

export default function App() {
  const ref = useRef(null);
  return (
    <div>
      <h1>Hello StackBlitz!</h1>
      <p ref={ref}> Start editing to see some magic happen :)</p>
    </div>
  );
}

When we add a ref prop to an element, like above, React associates the .current property of the ref object we passed, with the corresponding DOM element.

Fianlly, simply use the current property of the reference inside useEffect:

import * as React from 'react';
import { useRef, useEffect } from 'react';
import './style.css';

export default function App() {
  const ref = useRef(null);
  useEffect(() => {
    const el = ref.current;
    console.log(el);
  }, []);

  return (
    <div>
      <h1>Hello StackBlitz!</h1>
      <p ref={ref}> Start editing to see some magic happen :)</p>
    </div>
  );
}

You can play with the example on Stackblitz.

To ensure that the element's ref has been set and that it has been rendered to the DOM, we made use of the useEffect hook.

It's possible that the element you're trying to access by ID or via its ref directly in the render method of your function component hasn't rendered yet. This is why, you need to get the element inside useEffect. Accessing DOM elements is considered a side effect!