Course contentsShow
← React
Lesson 496 of 2,39614. Uncontrolled ComponentsFree lesson

Imperatively Focusing an Input

Call inputRef.current.focus() to programmatically move focus to an input, useful for UX enhancements.

Imperatively Focusing an Input

What you'll learn: How to programmatically move keyboard focus to an input using a ref, making your forms feel more polished and user-friendly.

The Core Idea

Sometimes you want to tell an input to grab focus without waiting for the user to click it. Maybe you want to focus a search box when a modal opens, or highlight an error field after validation fails. With uncontrolled components and refs, you can do this imperatively using the browser's native focus() method.

How It Works

Once you have a ref attached to an input (as you learned previously), inputRef.current holds the actual DOM element. Every DOM input has a built-in .focus() method. Call it, and the browser moves keyboard focus to that element:

function SearchForm() {
  const searchRef = useRef(null);

  function handleShowSearch() {
    searchRef.current.focus();
  }

  return (
    <div>
      <input ref={searchRef} type="text" placeholder="Search..." />
      <button onClick={handleShowSearch}>Focus Search</button>
    </div>
  );
}

When the button is clicked, searchRef.current.focus() runs and the cursor jumps into the search box—no clicking required.

Common Use Cases

  • Autofocusing a modal's first input when it opens
  • Highlighting error fields after form validation
  • Improving accessibility by managing keyboard navigation
  • Creating seamless UX flows (e.g., "Enter" submits and focuses the next field)

The Imperative Nature

This is called "imperative" because you're giving the browser a direct command: "focus this element now." It's not declarative like most React code, but refs make this kind of DOM manipulation safe and appropriate.

Key Takeaway: Call inputRef.current.focus() to programmatically move focus to an input, enabling better UX flows and accessibility patterns without relying on user clicks.