DEV Community

Coder
Coder

Posted on • Updated on

Focus next input in React

If you're building a form in React, you'll likely want to implement a way for users to quickly navigate between fields using the "tab" key. This can be achieved using the tabIndex and ref properties in React.

Here's how to implement keyboard navigation between form fields in React.

Setting up Refs

In order to focus the next input, we'll need to first create a "ref" for each input. This can be done using the useRef hook, like so:

import { useRef } from 'react';

function MyForm() {
  const nameRef = useRef(null);
  const emailRef = useRef(null);

  // rest of your component code here
}
Enter fullscreen mode Exit fullscreen mode

We're creating two refs here, one for the name input and one for the email input. We can then use these refs to focus the next input when the user presses the "tab" key.

Handling the Tab Key

Next, we'll need to handle the "tab" key press in our form. We can do this by adding an onKeyDown event listener to each input, like so:

function MyForm() {
  const nameRef = useRef(null);
  const emailRef = useRef(null);

  function handleKeyDown(event, ref) {
    if (event.key === 'Tab') {
      event.preventDefault();
      ref.current.focus();
    }
  }

  return (
    <form>
      <label>
        Name:
        <input ref={nameRef} onKeyDown={event => handleKeyDown(event, emailRef)} />
      </label>
      <label>
        Email:
        <input ref={emailRef} onKeyDown={event => handleKeyDown(event, nameRef)} />
      </label>
    </form>
  );
}
Enter fullscreen mode Exit fullscreen mode

Here, we're adding the onKeyDown event listener to each input. When the user presses the "tab" key, we call the preventDefault method to prevent the browser from focusing the next element automatically. We then call the focus method on the ref of the next input.

Note that we're passing the ref of the next input as an argument to the handleKeyDown function. This allows us to specify which input to focus next when the user presses the "tab" key.

Wrapping Up

And that's it! With these few lines of code, we've implemented keyboard navigation between form fields in React.

To recap:

  1. Create a ref for each input using the useRef hook
  2. Add an onKeyDown event listener to each input
  3. Handle the "tab" key press in the event listener by calling preventDefault and focus on the ref of the next input

With these steps, you'll have a form that allows for quick and easy navigation using the keyboard.

Happy coding!

Oldest comments (0)