JAVASCRIPT

Focus an Input Field with useRef

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 or user action.

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

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

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

  const handleClick = () => {
    // Focus the input on button click as well
    if (inputRef.current) {
      inputRef.current.focus();
    }
  };

  return (
    <div>
      <input type="text" ref={inputRef} placeholder="Enter text here" />
      <button onClick={handleClick}>Focus Input</button>
    </div>
  );
}

export default MyForm;
How it works: This snippet demonstrates `useRef` to gain direct access to a DOM element. The `inputRef` is attached to the `<input>` element. The `useEffect` hook, with an empty dependency array, ensures that the `focus()` method is called on the input element once when the component mounts. Additionally, the button click handler also utilizes `inputRef.current.focus()` to focus the input on demand, showcasing direct DOM manipulation capabilities.

Need help integrating this into your project?

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

Hire DigitalCodeLabs