How to Set Focus on an Input Element in React using Hooks


How to Set Focus on an Input Element in React using Hooks

In this tutorial, I will show you how to programmatically set the focus to an input element using React.js and hooks. We will use two hooks, useRef and useEffect.

Set up the Project

All you need is a functional component.

I have created a React app from scratch using create-react-app.

Then replace everything inside the App component with this:

import React from 'react';

function App() {
  return (
    <form>
      <input type="text" placeholder="Enter e-mail" />
      <input type="password" placeholder="Enter password" />
      <input type="submit" />
    </form>
  );
}

export default App;

Here we have created a simple login form.

Start the application by typing npm start in your command line and you should see this beautiful web page:

What is our Goal?

Our goal is to have the focus on the e-mail input when we refresh our browser. This way, the user can start writing their login credentials without clicking on the e-mail input.

Set a reference to the e-mail Input

The first thing we will do is to add a reference to our input element.

  1. Add useRef in our import statement.
  2. Call the useRef function and assign the result to a inputRef variable.
  3. Add a ref attribute to the e-mail input and assign the inputRef variable to it.

The component should look like this:

import React, { useRef } from 'react';

function App() {

  const inputRef = useRef();

  return (
    <form>
      <input type="text" placeholder="Enter e-mail" ref={inputRef} />
      <input type="password" placeholder="Enter password" />
      <input type="submit" />
    </form>
  );
}

export default App;

Set Focus to the Input Element With useEffect

Now that we have added a reference to our input element, we can use that reference to set focus.

However, we can’t just set focus to the element directly in out App function. We have to wait until the rendering has completed.

We can do that with the useEffect hook. With useEffect, the code inside will run after the component has rendered. We can focus the input element by executing the focus function on the current object.

The finished result will look like this:

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

function App() {

  const inputRef = useRef();

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

  return (
    <form>
      <input type="text" placeholder="Enter e-mail" ref={inputRef} />
      <input type="password" placeholder="Enter password" />
      <input type="submit" />
    </form>
  );
}

export default App;

When we refresh our page, we can see that the e-mail input is focused and the user can start typing immediately.

Rooney

I am a full-stack web developer with over 13 years of experience. I love learning new things and are passionate about JavaScript development both on the front-end and back-end.

Recent Content