DEV Community

Mohamed Idris
Mohamed Idris

Posted on

Using `useRef` to Set Focus on an Input Field

The useRef hook allows you to interact with DOM elements directly in React without causing re-renders. One common use case is setting focus on an input field when the component mounts.

Example: Set Focus on an Input Field

  1. Create a ref for the input field:
const refContainer = useRef(null);
Enter fullscreen mode Exit fullscreen mode
  1. Set focus after the component mounts:
useEffect(() => {
  refContainer.current.focus();
}, []);
Enter fullscreen mode Exit fullscreen mode

Full Example:

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

const App = () => {
  // State to track the value
  const [value, setValue] = useState(0);

  // Creating a ref to access the input field
  const refContainer = useRef(null);

  // useEffect hook that runs after each render
  // It focuses the input field every time the component re-renders
  useEffect(() => {
    refContainer.current.focus(); // Focuses the input field
  });

  // The code below could also use an empty dependency array to run only once after the first render:
  // useEffect(() => {
  //   refContainer.current.focus(); // Focuses the input field after the component mounts
  // }, []);

  return (
    <div>
      <form>
        {/* Attach the ref to the input field */}
        <input type="text" ref={refContainer} />
      </form>
      {/* Display the current value */}
      <h1>Value: {value}</h1>
      {/* Button to increase the value */}
      <button onClick={() => setValue(value + 1)}>Increase</button>
    </div>
  );
};

export default App;
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • useRef(null): Creates a reference to the input field, allowing direct DOM manipulation (e.g., setting focus).

  • useEffect: Runs after every render. The code inside focuses on the input field using refContainer.current.focus(). If you want it to only run after the initial render, you could use an empty dependency array [].

  • Input Field: The ref={refContainer} attaches the useRef to the input, giving you access to its DOM element.

Top comments (0)