Categories
React Answers

What is the Equivalent of document.getElementById() in React?

Spread the love

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.

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
</>
);
}

Leave a Reply

Your email address will not be published.

If you like the content of this blog, subscribe to my email list to get exclusive articles not available to anyone else.