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!
- Author: Ahmed Bouchefra Follow @ahmedbouchefra
-
Date:
Related posts
Reset file input with React Get an element by ID in React Using the substring method with React Understanding React 18 root API: ReactDOM.createRoot React 18 useEffect runs twice Handling Arrays with React 18 useState Upgrade to React Router 6 React setState not merging nested state as expected React Router 6 tutorial with examples Remove an element from a useState Array in React 18 Update Arrays with React useState Hook Without Push React state array: get length example React 18 upgrade guide and new features React Router 5.1+ Hooks