Categories
React Answers

How to Focus on the Next Field When Pressing Enter in React?

Spread the love

Sometimes, we want to focus on the next field when pressing enter in React.

In this article, we’ll look at how to focus on the next field when pressing enter in React.

Focus on the Next Field When Pressing Enter in React

To focus on the next field when pressing enter in React, we can set the onKeyDown prop of the inputs to a function that gets the next input and call focus on it.

To do this, we write:

import React from "react";

export default function App() {
  const handleEnter = (event) => {
    if (event.key.toLowerCase() === "enter") {
      const form = event.target.form;
      const index = [...form].indexOf(event.target);
      form.elements[index + 1].focus();
      event.preventDefault();
    }
  };

  return (
    <form>
      <input onKeyDown={handleEnter} placeholder="field 1" />
      <input onKeyDown={handleEnter} placeholder="field 2" />
      <input placeholder="field 3" />
    </form>
  );
}

We have the handleEnter function that checks if the pressed key is Enter by checking the event.key property.

Then we get the form element that the input is in with the event.target.form property.

Next, we spread the form iterable object into an array and then call indexOf of it with event.target to get the index of the input we’re currently focused on.

And then we get the next input with form.elements[index + 1] to get the next input and call focus on it.

Finally, we call event.preventDefault to prevent the default browser behavior of pressing enter which we don’t want.

Now when we press enter, the focus will be switched to the next input.

Conclusion

To focus on the next field when pressing enter in React, we can set the onKeyDown prop of the inputs to a function that gets the next input and call focus on it.

By John Au-Yeung

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

Leave a Reply

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