Borislav Hadzhiev
Thu Apr 28 2022·2 min read
Photo by Jonathan Leppan
To get an element by ID in React:
ref
prop on the element.current
property to access the element in the useEffect
hook.import {useRef, useEffect} from 'react'; export default function App() { const ref = useRef(null); useEffect(() => { // 👇️ use document.getElementById() const el = document.getElementById('my-element'); console.log(el); // 👇️ (better) use a ref const el2 = ref.current; console.log(el2); }, []); return ( <div> <h2 ref={ref} id="my-element"> Some content here </h2> </div> ); }
The code snippet shows how to get element by ID using the
document.getElementById()
method and via a ref
.
The useRef() hook can be
passed an initial value as an argument. The hook returns a mutable ref object
whose .current
property is initialized to the passed argument.
current
property on the ref object to get access to the h2
element on which we set the ref
prop.When we pass a ref prop to an element, e.g. <div ref={myRef} />
, React sets
the .current
property of the ref object to the corresponding DOM node.
We passed an empty dependencies array to the useEffect hook, so it's only going to run when the component mounts.
useEffect(() => { // 👇️ use document.getElementById() const el = document.getElementById('my-element'); console.log(el); // 👇️ (better) use a ref const el2 = ref.current; console.log(el2); }, []);
We used the useEffect
hook because we want to make sure the ref
has been set
on the element and the element has been rendered to the DOM.
Alternatively, you can use the document.getElementById
method if you don't
have access to the element and can't set a ref
prop on it.
useEffect(() => { // 👇️ use document.getElementById() const el = document.getElementById('my-element'); console.log(el); }, []);
You have to call the document.getElementById()
method in the useEffect
hook
or when an event occurs.
Here is an example that gets an element by ID when an event occurs.
import {useRef} from 'react'; export default function App() { const ref = useRef(null); const handleClick = () => { // 👇️ use document.getElementById() const el = document.getElementById('my-element'); console.log(el); // 👇️ (better) use a ref const el2 = ref.current; console.log(el2); }; return ( <div> <h2 ref={ref} id="my-element"> Some content here </h2> <button onClick={handleClick}>Click</button> </div> ); }
Selecting an element by ID or using a ref is also possible in an event handler function.
ref
directly in the render
method of your function component, the element you are trying to access might not have rendered yet.The useEffect
hook runs after the DOM elements in the component have been
rendered to the DOM, so if an element with the provided id
exists, it will be
selected.