# Table of Contents
- Get an element by ID using a ref in React
- Get an element by ID using document.getElementById
- Get an element by ID when an Event occurs in React
- [Solved] document.getElementById() returns NULL in React
# Get an element by ID using a ref
in React
To get an element by ID using a ref:
- Set the
ref
prop on the element. - Use the
current
property to access the element in theuseEffect
hook.
App.js
Copied!
import {useRef, useEffect} from 'react';export default function App() { const ref = useRef(null); useEffect(() => { const element = ref.current; console.log(element); console.log(element.id); }, []); return ( <div> <h2 ref={ref} id="box"> bobbyhadz.com </h2> </div> );}
The code for this article is available on GitHub
The equivalent of getting an element by ID in React is to use a ref
.
The useRef() hook can be passed aninitial value as an argument.
App.js
Copied!
const ref = useRef(null);
The hook returns a mutable ref object whose .current
property is initializedto the passed argument.
We set the ref
prop on the element we need to access.
App.js
Copied!
<h2 ref={ref} id="box"> bobbyhadz.com</h2>
Notice that we have to access the current
property on the ref object to get access to the h2
element on which we set the ref
prop.
App.js
Copied!
useEffect(() => { const element = ref.current; console.log(element); console.log(element.id);}, []);
When we pass a ref prop to an element, e.g. <div ref={myRef} />
, React setsthe .current
property of the ref object to the corresponding DOM node.
We passed an empty dependencies array to theuseEffect hook, so it's onlygoing to run when the component mounts.
App.js
Copied!
useEffect(() => { const element = ref.current; console.log(element); console.log(element.id);}, []);
We used the useEffect
hook because we want to make sure the ref
has been seton the element and the element has been rendered to the DOM.
The useRef
hook is the React.js equivalent of the document.getElementById
method in JavaScript.
However, you are still able to use the method in React.js as well.
If you don't have access to the element you are trying to select in yourcomponent and can't simply set the ref
prop on it, use thedocument.getElementById()
method.
I've also written a tutorial onhow to get the ID of an element on click.
# Get an element by ID using document.getElementById
This is a two-step process:
- Use the
useEffect
hook to invoke a function once the component mounts. - Use the
document.getElementById()
method in theuseEffect
hook.
App.js
Copied!
import {useEffect} from 'react';export default function App() { useEffect(() => { const element = document.getElementById('box'); console.log(element); console.log(element.id); }, []); return ( <div> <h2 id="box">bobbyhadz.com</h2> </div> );}
The code for this article is available on GitHub
Thedocument.getElementById()method takes an ID as a parameter and returns the element with the given ID.
You have to call the document.getElementById()
method in the useEffect
hookor when an event occurs.
A commonly used convention in React is to only use the document.getElementById
method when you don't have access to the DOM element and can't set a ref
onit.
# Get an element by ID when an Event occurs in React
Here is an example that gets an element by ID when an event occurs.
App.js
Copied!
import {useRef} from 'react';export default function App() { const ref = useRef(null); const handleClick = () => { // 👇️ use document.getElementById() const element = document.getElementById('box'); console.log(element); // 👇️ (better) use a ref const element2 = ref.current; console.log(element2); }; return ( <div> <h2 ref={ref} id="box"> bobbyhadz.com </h2> <button onClick={handleClick}>Click</button> </div> );}
The code for this article is available on GitHub
Selecting an element by ID or using a ref
is also possible in an event handlerfunction.
If you try to get an element by ID or via its ref
directly in the render
method of your function component, the element you are trying to access might not have been rendered yet.
The useEffect
hook runs after the DOM elements in the component have beenrendered to the DOM, so if an element with the provided id
exists, it will beselected.
You can also use thedocument.querySelector method in React.
# [Solved]: document.getElementById() returns NULL in React
The document.getElementById()
method returns null
in React when we callthe method before the element with the provided ID has been rendered to the DOMor if an element with the ID doesn't exist.
To get around this, call the getElementById()
method in the useEffect
hook.
App.js
Copied!
import {useEffect} from 'react';export default function App() { useEffect(() => { // 👇️ call method in useEffect hook const el = document.getElementById('container'); console.log(el); }, []); return ( <div> <div id="container"> <h2>bobbyhadz.com</h2> </div> </div> );}
The code for this article is available on GitHub
The 2 most common reasons for thedocument.getElementById()method to return null
in React are:
- Trying to select an element that hasn't been rendered to the DOM yet.
- Supplying an ID that doesn't exist in the DOM.
# Use document.getElementById
in the useEffect
hook
You can use the document.getElementById
method in theuseEffect hook because the hookruns after the component has been mounted.
App.js
Copied!
useEffect(() => { // 👇️ call method in useEffect hook const el = document.getElementById('container'); console.log(el);}, []);
We passed an empty dependencies array to the useEffect
hook, so it's onlygoing to run on the initial render.
We had to use the useEffect
hook because we need to wait for the div
element to get rendered before calling document.getElementById()
.
You can also call the document.getElementById()
method in an event handlerfunction, e.g. in an onClick
handler because the element will be present inthe DOM when the event is triggered.
# Using a ref
instead of document.getElementById()
Note that if you have access to the DOM element in your component, you can use aref
.
App.js
Copied!
import {useRef, useEffect} from 'react';export default function App() { const ref = useRef(null); useEffect(() => { const el = ref.current; console.log(el); }, []); return ( <div> <div ref={ref}> <h2>bobbyhadz.com</h2> </div> </div> );}
The code for this article is available on GitHub
The useRef() hook can be passed aninitial value as an argument. The hook returns a mutable ref object whose.current
property is initialized to the passed argument.
Notice that we have to access the current
property on the ref object to get access to the div
element on which we set the ref
prop.
App.js
Copied!
useEffect(() => { const el = ref.current; console.log(el);}, []);
When we pass a ref prop to an element, e.g. <div ref={myRef} />
, React setsthe .current
property of the ref object to the corresponding DOM node.
We used the useEffect
hook because we want to make sure the ref
has been seton the element and the element has been rendered to the DOM.
Using refs should be your preferred approach when you have access to the elementin your component, otherwise, you can use the document.getElementById
method.