← Back to all snippets
JAVASCRIPT

Direct DOM Interaction with `useRef` to Focus an Input

Learn how to use the `useRef` hook in React to directly interact with DOM elements, such as programmatically focusing an input field on component mount.

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

export function AutoFocusInput() {
  const inputRef = useRef(null);

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

  return (
    <div>
      <label htmlFor="autofocus-input">Your Name:</label>
      <input id="autofocus-input" type="text" ref={inputRef} />
    </div>
  );
}
How it works: The `useRef` hook allows you to create a mutable ref object whose `.current` property can hold any mutable value. Here, it's used to directly access a DOM element. By attaching `inputRef` to the `<input>` element, `inputRef.current` will point to the actual DOM node. The `useEffect` then uses this ref to call the `focus()` method on the input element once the component has mounted, providing direct imperative control over the DOM.

Need help integrating this into your project?

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

Hire DigitalCodeLabs