Start learning free

LESSON 152 OF 161 · FRONTEND: INTERVIEW QUESTIONS

Multi-Step Form in JavaScript

Practice

A multi-step form shows one part at a time. One number in state, step, picks the field, the Step 2 of 3 line and the buttons. The name and the email are state too, so they keep their values when their field leaves the screen, and Back shows them again.

Before Next moves on, it checks the field of this step. If the field is not right, it sets an error message and returns early, so the step doesn't change. The message shows in a paragraph with role="alert", which screen readers read out at once. It must also go away: when the field is right, and when the visitor goes Back.

A check with an early return, on another form:

function applyCoupon() {
  if (code.length !== 6) return setMessage("Codes have 6 letters.");
  setMessage("");
  setApplied(true);
}

The last step lists what was entered and has a Submit button. Submit turns a sent state to true, and then the component returns just a thank-you instead of the form.

The check fills the form, with two mistakes on the way. Your page must show:

> open the page                 →  text: Step 1 of 3, field "Name"
> click "Next"                  →  alert: Enter your name.
> type "Eva Rossi", click "Next"  →  text: Step 2 of 3, field "Email", button: Back (no alert)
> type "eva.example.com", click "Next"  →  alert: Enter an email with @ in it.
> click "Back"                  →  text: Step 1 of 3, field "Name": "Eva Rossi" (no alert)
> click "Next", type "eva@example.com", click "Next"
      text: Step 3 of 3
      item: Name: Eva Rossi
      item: Email: eva@example.com
      button: Back, button: Submit
> click "Submit"                →  status: Thanks, Eva Rossi!

Your task: the step, name and email state, the two fields, next, back and the Next and Back buttons are already in src/App.jsx. Add the error state, the name and email checks in next, the alert, the clearing of the message, the list on step 3, and a Submit that ends with Thanks, …!.


Assignment
Follow the Coding Tutorial to make the sign-up form check each step before Next, show and clear its messages, and end with a thank-you.


Hint
Each check is one line: if (…) return setError(…);, so nothing below it runs. Every way of leaving a step, Next with a good field or Back, sets error to "".


STEP 1 OF 10
    Ctrl + Enter to check

    Fe Multi Step Form in JavaScript

    Keep going with JavaScript1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free