← Back to all snippets
JAVASCRIPT

Focusing an Input Field with useRef

Learn how to use React's `useRef` hook to directly access and manipulate DOM elements, such as programmatically focusing an input field after component mount.

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

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

  useEffect(() => {
    // Focus the input field when the component mounts
    if (inputRef.current) {
      inputRef.current.focus();
    }
  }, []); // Empty dependency array ensures this runs only once after initial render

  return (
    <div>
      <label htmlFor="myInput">Name:</label>
      <input id="myInput" type="text" ref={inputRef} placeholder="Type here..." />
    </div>
  );
}

export default FocusInputComponent;
How it works: This snippet demonstrates the `useRef` hook to gain direct access to a DOM element. We create a ref with `useRef(null)` and attach it to an input element using the `ref` attribute. Inside a `useEffect` hook with an empty dependency array (meaning it runs once after the initial render), we check if `inputRef.current` exists, then call its `focus()` method to programmatically focus the input field when the component first mounts.

Need help integrating this into your project?

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

Hire DigitalCodeLabs