Borislav Hadzhiev
Mon May 02 2022·2 min read
Photo by Debbie Pan
The equivalent of the document.querySelector()
method in React is using
refs. To select an element, set the ref
prop on it to the return value of
calling the useRef()
hook and access the dom element using the current
property on the ref
, e.g. ref.current
.
import {useRef, useEffect} from 'react'; export default function App() { const ref = useRef(null); useEffect(() => { // 👇️ use a ref (best) const el2 = ref.current; console.log(el2); // 👇️ use document.querySelector() // should only be used when you can't set a ref prop on the element // (you don't have access to the element) const el = document.querySelector('#container'); console.log(el); }, []); return ( <div> <div ref={ref} id="container"> <h2>Some content here</h2> </div> </div> ); }
The useRef() hook can be
passed an initial value as an argument. The hook returns a mutable ref object
whose .current
property is initialized to the passed argument.
current
property on the ref object to get access to the div
element on which we set the ref
prop.const el2 = ref.current; console.log(el2);
When we pass a ref prop to an element, e.g. <div ref={myRef} />
, React sets
the .current
property of the ref object to the corresponding DOM node.
We passed an empty dependencies array to the useEffect hook, so it's only going to run when the component mounts.
useEffect(() => { const el2 = ref.current; console.log(el2); }, []);
useEffect
hook because we want to make sure the ref
has been set on the element and the element has been rendered to the DOM.Note that you don't have to set an id
on the element when accessing it using a
ref
.
Here is a minimal example of using a ref
in React.
import {useRef, useEffect} from 'react'; export default function App() { const ref = useRef(null); useEffect(() => { const el2 = ref.current; console.log(el2); }, []); return ( <div> <div ref={ref}> <h2>Some content here</h2> </div> </div> ); }
If you don't have access to the element you are trying to select in your
component and can't simply set the ref
prop on it, use the
document.querySelector
method.
import {useEffect} from 'react'; export default function App() { useEffect(() => { // 👇️ use a ref (best) const el = document.querySelector('#container'); console.log(el); }, []); return ( <div> <div id="container"> <h2>Some content here</h2> </div> </div> ); }
You have to call the document.querySelector()
method in the useEffect
hook
or when an event occurs.
For example, you can safely access the current
property of a ref
in an
onClick
event handler because the element will be present in the DOM when the
event is triggered.
document.querySelector
or a ref
directly in the render
method of your function component, the element might not have rendered yet.The useEffect
hook runs after the DOM elements in the component have been
rendered to the DOM, so if an element with the provided id
exists, it will be
selected.