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.
One reply on “What is the Equivalent of document.getElementById() in React?”
This code is probably not doing what you’re expecting UNTIL the component re-renders because you’re setting the ref to a DOM element that doesn’t exist yet. Your console log will always say null the first time the component renders. A better way to do it is:
export default function App() {
const myContainer = useCallback((myContainer) => {
if (myContainer !== null) {
console.log(myContainer);
}
}, []);
return (
<>
I can use the DOM with react ref
</>
);
}