Attaching Refs to Input Elements
What you'll learn: How to connect a ref object to an input element so you can access its DOM node directly.
Making the Connection
In the previous lesson, you created a ref object with useRef. Now you need to actually attach that ref to an input element. This is how you tell React which DOM element you want to reference.
The connection is simple: pass your ref object to the input's ref prop.
import { useRef } from 'react';
function MyForm() {
const inputRef = useRef(null);
return (
<input
type="text"
ref={inputRef}
/>
);
}
How It Works
When React renders this input to the DOM, it automatically stores the actual DOM node inside inputRef.current. Think of it like React taking the physical input element and placing it in the .current property of your ref object for safekeeping.
Before the component mounts, inputRef.current is null (the initial value you passed to useRef). After React commits the component to the DOM, inputRef.current becomes the actual <input> DOM element.
The ref Prop
The ref prop is special — it's built into React just like key. You can attach refs to any HTML element (<input>, <div>, <button>, etc.) or custom components (with forwarding, which you haven't learned yet).
Why This Matters
With the ref attached, you now have a direct line to the DOM node. In upcoming lessons, you'll use inputRef.current to read the input's value, focus it, or perform other imperative DOM operations — all without controlling the input through state.
Key Takeaway: Pass your ref object to an element's ref prop to establish the connection; React will populate ref.current with the DOM node after rendering.