Categories
React Answers

How to Set Focus On Input After Render in a React Component?

Spread the love

Sometimes, we want to set focus on an input element in a React component after rendering it.

In this article, we’ll look at how to set focus on an input element in a React component after rendering it.

Set Focus On Input After Render

To focus an input, we have to use the native DOM element focus method to do it. The method is available to input elements so we can call it.

We can use the useEffect hook to run something when the component renders. If we pass in an empty array as the 2nd argument, then the callback we pass into useEffect only runs when the component first loads.

For instance, we can write the following to do that:

import React from "react";

export default function App() {
  const input = React.createRef();
  React.useEffect(() => input.current.focus(), []);
  return (
    <div className="App">
      <input ref={input} />
    </div>
  );
}

In the code above, we have the useEffect hook and the input ref created with the createRef method, which passed into the ref prop of the input.

Then in the useEffect callback, we call input.current.focus() to call the focus method of our input element.

In the end, when we load the page, we’ll see that the input is focused when App loads as we desired.

Conclusion

To focus an input, we have to use the native DOM element focus method to do it. The method is available to input elements so we can call it.

We can use the useEffect hook to run something when the component renders. If we pass in an empty array as the 2nd argument, then the callback we pass into useEffect only runs when the component first loads.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

One reply on “How to Set Focus On Input After Render in a React Component?”

This is only if there is one input field.. what if there is are many input fields rendered using a .map()? how would we set the current ref? (it has to be the one the user last clicked on)

Leave a Reply

Your email address will not be published. Required fields are marked *