The ref Prop: Accessing DOM Nodes Directly
What you'll learn: How to use the ref prop to grab a direct reference to an actual HTML element in the browser's DOM.
The Core Idea
So far, you've used useRef to store mutable values that persist between renders. But useRef has another superpower: when you pass a ref object to a JSX element's ref prop, React automatically stores the underlying DOM node in ref.current.
Think of it like putting a sticky note on a specific element in your UI. Instead of searching through the entire DOM tree later, you can grab that element instantly through your ref.
How It Works
When React renders your component and creates the real DOM elements, it looks for any ref props. If it finds one, React sets ref.current to point to that actual DOM node. Now you have direct access to call browser methods like .focus(), .scrollIntoView(), or .getBoundingClientRect().
function MyInput() {
const inputRef = useRef(null);
function handleClick() {
inputRef.current.focus(); // Direct DOM manipulation!
}
return (
<>
<input ref={inputRef} />
<button onClick={handleClick}>Focus the input</button>
</>
);
}
Notice how inputRef.current is the actual <input> DOM element—the same one you'd get from document.querySelector.
When to Use This
The ref prop shines when you need to:
- Focus an input programmatically
- Measure element dimensions
- Scroll to specific positions
- Integrate with third-party DOM libraries
Key Takeaway: The ref prop connects a useRef object to a real DOM node, giving you direct access to browser APIs when React's declarative approach isn't enough.