How to get an element by ID in React
In this tutorial, we are going to learn how to get an element by ID in React with the help of an example.
Consider, that we have a component like this.
import React from "react";
function App() {
return (
<div>
<button>Add</button> </div>
);
}
Now, we need to get the above button by ID in react.
To get an element by id in react:
-
First, add the
id
attribute to the element you want to access. -
Call the document.getElementById() method by passing the
id
inside the useEffect() hook.
Here is an example:
import React, { useEffect } from "react";
function App() {
useEffect(() => {
// id name is "my-btn"
const btn = document.getElementById("my-btn");
console.log(btn);
}, []);
return (
<div>
<button id="my-btn">Add</button>
</div>
);
}
Output:
<button id="my-btn">Add</button>
But React recommends us to use refs for accessing the dom elements in hooks or event handler functions.
Here is an example of how to get the particular element in react using the useRef hook:
import React, { useEffect, useRef } from "react";
function App() {
const btnRef = useRef(null);
useEffect(() => {
const btn = btnRef.target;
console.log(btn);
}, []);
return (
<div>
<button ref={btnRef}>Add</button>
</div>
);
}
export default App;