0
0
ReactHow-ToBeginner · 3 min read

How to Focus Input Using useRef in React

In React, you can focus an input element by creating a ref with useRef and attaching it to the input. Then call ref.current.focus() to set focus programmatically.
📐

Syntax

Use useRef to create a reference object. Attach it to the input element using the ref attribute. Access the input element via ref.current and call focus() to set focus.

  • useRef(): Creates a mutable ref object.
  • ref attribute: Connects the ref to the input element.
  • ref.current.focus(): Focuses the input element.
jsx
import React, { useRef } from 'react';

function Component() {
  const inputRef = useRef(null);

  function handleFocus() {
    inputRef.current.focus();
  }

  return (
    <>
      <input ref={inputRef} type="text" />
      <button onClick={handleFocus}>Focus Input</button>
    </>
  );
}
💻

Example

This example shows a text input and a button. Clicking the button sets focus to the input using useRef. The input gets a blue outline when focused, showing the focus effect.

jsx
import React, { useRef } from 'react';

export default function FocusInputExample() {
  const inputRef = useRef(null);

  const focusInput = () => {
    if (inputRef.current) {
      inputRef.current.focus();
    }
  };

  return (
    <div style={{ padding: '1rem' }}>
      <input
        ref={inputRef}
        type="text"
        placeholder="Click the button to focus me"
        style={{ padding: '0.5rem', fontSize: '1rem', border: '2px solid #ccc', borderRadius: '4px' }}
        aria-label="Sample input"
      />
      <button
        onClick={focusInput}
        style={{ marginLeft: '1rem', padding: '0.5rem 1rem', fontSize: '1rem' }}
        aria-label="Focus the input"
      >
        Focus Input
      </button>
    </div>
  );
}
Output
A text input box and a button labeled 'Focus Input'. Clicking the button moves the cursor and focus to the input box, showing a focus outline.
⚠️

Common Pitfalls

  • Not attaching the ref to the input element causes ref.current to be null, so focus() fails.
  • Calling focus() before the input renders will cause errors.
  • Using document.getElementById instead of useRef breaks React's declarative model.
jsx
import React, { useRef } from 'react';

function WrongFocus() {
  const inputRef = useRef(null);

  function handleFocus() {
    // Wrong: ref not attached, ref.current is null
    if (inputRef.current) {
      inputRef.current.focus();
    } else {
      console.log('ref.current is null');
    }
  }

  return (
    <>
      <input type="text" /> {/* Missing ref={inputRef} */}
      <button onClick={handleFocus}>Focus Input</button>
    </>
  );
}

function RightFocus() {
  const inputRef = useRef(null);

  function handleFocus() {
    inputRef.current.focus();
  }

  return (
    <>
      <input ref={inputRef} type="text" />
      <button onClick={handleFocus}>Focus Input</button>
    </>
  );
}
📊

Quick Reference

Steps to focus input using useRef:

  • Create a ref with const ref = useRef(null);
  • Attach it to input: <input ref={ref} />
  • Call ref.current.focus() to focus
  • Ensure the input is rendered before calling focus

Key Takeaways

Create a ref with useRef and attach it to the input element using the ref attribute.
Call ref.current.focus() to programmatically set focus on the input.
Always ensure the input is rendered before calling focus to avoid errors.
Avoid manipulating DOM directly; use useRef for React-friendly access.
Check that ref.current is not null before calling focus to prevent runtime errors.