TypeOfNaN

How to set focus on an input field after rendering in React

Nick Scialli
June 24, 2021

focusing on input

When a component renders, you may need to automatically set focus on an input. In this post, we look at how we can quickly accomplish this.

An example problem

Let’s use a very simple example: we have an App component that renders a name text input as follows:

export default function App() {
  return (
    <div className="App">
      <label htmlFor="name">Name: </label>
      <input id="name" />
    </div>
  );
}

Now, we want to set focus immediate to that name input.

Getting a reference to the input

Our first step will be getting a reference to the input DOM element. We can do this by using the useRef hook:

import { useRef } from 'react';

export default function App() {
  const inputRef = useRef();

  return (
    <div className="App">
      <label htmlFor="name">Name: </label>
      <input id="name" ref={inputRef} />
    </div>
  );
}

Great! We now have a reference to our input. But how do we set the focus on it on render?

The useEffect hook

In the class component days of React, we’d reach for the componentDidMount method to take an action when the component mounts. Now, with function components, we use the useEffect hook. Specifically, we can use this hook with an empty dependency array to make sure it only fires when the component intially mounts:

import { useRef, useEffect } from 'react';

export default function App() {
  const inputRef = useRef();

  useEffect(() => {
    // Focus here
  }, []);

  return (
    <div className="App">
      <label htmlFor="name">Name: </label>
      <input id="name" ref={inputRef} />
    </div>
  );
}

Setting focus

Now all we need to do is set focus. inputRef.current will be a reference to the underlying DOM node, so we just need to call the focus method on this node.

All together, our solution looks like this:

import { useRef, useEffect } from 'react';

export default function App() {
  const inputRef = useRef();

  useEffect(() => {
    inputRef.current.focus();
  }, []);

  return (
    <div className="App">
      <label htmlFor="name">Name: </label>
      <input id="name" ref={inputRef} />
    </div>
  );
}

And there you have it! The input will now automatically be focused when the component renders.

Nick Scialli

Nick Scialli is a senior UI engineer at Microsoft.

© 2024 Nick Scialli