JAVASCRIPT

How to Auto-Focus an Input Field in React with `useRef`

Master React's `useRef` hook to auto-focus input fields or interact directly with DOM elements on component mount, improving user experience and accessibility effectively.

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

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

  useEffect(() => {
    // Focus the input element when the component mounts
    if (inputRef.current) {
      inputRef.current.focus();
    }
  }, []); // Empty dependency array ensures it runs only once on mount

  return (
    <div>
      <label htmlFor="autofocus-input">Enter your name:</label>
      <input
        id="autofocus-input"
        type="text"
        ref={inputRef}
        placeholder="Your name"
        aria-label="Your name"
      />
      <p>This input field should automatically gain focus when the component renders.</p>
    </div>
  );
}

export default FocusInput;
How it works: This snippet demonstrates `useRef` to interact directly with the DOM. `inputRef` is created and attached to the input element via the `ref` prop. The `useEffect` hook, with an empty dependency array, ensures that `inputRef.current.focus()` is called only once after the initial render, automatically focusing the input field when the component mounts.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs