Sometimes, we want to select a DOM element like we do with document.getElementById
in React.
In this article, we’ll look at what is the equivalent of document.getElementById
in React.
What is the Equivalent of document.getElementById() in React
The equivalent of document.getElementById
in React is refs.
We can assign a ref to an element and then retrieve the element that’s assigned the ref from the ref’s current
property.
For instance, we write:
import React, { useRef } from "react";
export default function App() {
const myContainer = useRef(null);
console.log(myContainer.current);
return (
<>
<div ref={myContainer}>I can use the DOM with react ref</div>
</>
);
}
to create a ref with the useRef
hook and assign it to myContainer
.
Then we assign the ref to the div by setting the ref
prop of the div to myContainer
.
Finally, we get the div by using the myContainer.current
property.
Therefore, the console log should log the div as the value.
Conclusion
The equivalent of document.getElementById
in React is refs.
We can assign a ref to an element and then retrieve the element that’s assigned the ref from the ref’s current
property.