Course contentsShow
← React
Lesson 714 of 2,39619. useRefFree lesson

Creating and Attaching Refs to Elements

Using useRef to create a ref object and attaching it to JSX elements via the ref prop.

Creating and Attaching Refs to Elements

What you'll learn: How to create a ref with useRef and connect it to a DOM element using the ref prop.


The Core Idea

You've learned that useRef creates a mutable box that survives re-renders. Now it's time to connect that box to actual DOM elements in your JSX. React provides a special ref prop that you can attach to any HTML element. When React renders that element, it automatically assigns the real DOM node to your ref's .current property.

Think of it like giving React a labeled container and saying: "When you create this <input> element, please put a reference to it in this container so I can access it later."

The Pattern

Here's the two-step process:

function MyComponent() {
  // Step 1: Create the ref object
  const inputRef = useRef(null);

  // Step 2: Attach it to a JSX element via the ref prop
  return <input ref={inputRef} type="text" />;
}

After the component renders, inputRef.current will contain the actual DOM node (the <input> element). Before the first render, it's null (which is why we initialize it with null).

Why This Matters

This connection lets you bypass React's declarative model when you need direct DOM access. You can now call methods like inputRef.current.focus() or read properties like inputRef.current.value directly.

The ref prop works on any HTML element: <div>, <button>, <canvas>, <video> — anything that becomes a real DOM node.

Key Takeaway: Create a ref with useRef(null), then attach it to any JSX element using the ref prop — React fills ref.current with the actual DOM node after rendering.