TypeOfNaN

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

Nick Scialli
June 24, 2021

New — Check out my free newsletter on how the web works!

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.

🎓 Learn how the web works

One of the best ways to level up your tech career is to have a great foundational understanding of how the web works. In my free newsletter, How the Web Works, I provide simple, bite-sized explanations for various web topics that can help you boost your knowledge. Join 2,500+ other learners on the newsletter today!

Signing up is free, I never spam, and you can unsubscribe any time. You won't regret it!

Sign up for the newsletter »
Nick Scialli

Nick Scialli is a senior UI engineer at Microsoft.

© 2024 Nick Scialli