React: Move focus through a form

Good forms move the cursor for the user: Enter goes to the next field, and a failed submit puts the cursor where the problem is.

What to build

A three-field form with keyboard-friendly focus handling.

Requirements

  • Uncontrolled inputs with the ids first, last and email, and a submit button Send.
  • Pressing Enter in first or last moves the focus to the next field instead of submitting.
  • On submit (without reloading): if a field is empty, focus the first empty one and show a p with the class error: Please fill in FIELD (with FIELD being first, last or email); otherwise show a p with the class done: Thanks, FIRST LAST and no error.

Constraints

Use refs to move the focus.

Example

Typing "Ada", pressing Enter, then pressing Send puts the cursor in the last-name field and says "Please fill in last".

Why it works

Refs give the handlers the real input elements, so they can read values and move focus exactly where the user needs it, without state for anything the page does not show.

Hints

Hint 1

Keep refs for the three inputs, for example in an array of refs, and move focus with ref.current.focus().

Hint 2

On submit, find the first empty field, focus it, and show an error naming it.

Solution

Show one correct solution (try it yourself first)
import { useRef, useState } from "react";

const FIELDS = ["first", "last", "email"];

export default function App() {
  const refs = [useRef(null), useRef(null), useRef(null)];
  const [message, setMessage] = useState(null);

  function handleKeyDown(event, index) {
    if (event.key === "Enter" && index < FIELDS.length - 1) {
      event.preventDefault();
      refs[index + 1].current.focus();
    }
  }

  function handleSubmit(event) {
    event.preventDefault();
    const empty = refs.findIndex((r) => r.current.value.trim() === "");
    if (empty >= 0) {
      refs[empty].current.focus();
      setMessage({ kind: "error", text: "Please fill in " + FIELDS[empty] });
    } else {
      setMessage({ kind: "done", text: "Thanks, " + refs[0].current.value + " " + refs[1].current.value });
    }
  }

  return (
    <form onSubmit={handleSubmit}>
      {FIELDS.map((name, i) => (
        <input key={name} id={name} ref={refs[i]} onKeyDown={(e) => handleKeyDown(e, i)} />
      ))}
      <button type="submit">Send</button>
      {message && <p className={message.kind}>{message.text}</p>}
    </form>
  );
}

Lesson: Refs: remembering without rendering →