Not only React anymoreStepperize now runs in Vue, Svelte, Solid, Angular, Lit, and HTML
Skip to Content
Stepperize

The URL as the current step

Keep the step in the URL with SvelteKit, in both directions.

The step option makes the flow follow a value that lives somewhere else. Pass the options as a function so they are read again when the page changes.

src/routes/checkout/[step]/+page.svelte
<script lang="ts">
  import { goto } from "$app/navigation";
  import { page } from "$app/state";
  import { checkout } from "#lib/checkout.js";

  const stepper = checkout.useStepper(() => ({
    linear: true,
    // The URL moves (a link, the back button): the flow follows.
    step: page.params.step,
    // The flow moves: push the new step.
    onChange: (snapshot) => {
      if (snapshot.step !== page.params.step) goto(`/checkout/${snapshot.step}`);
    },
    // The URL asks for a step the flow cannot be on: correct it without a history entry.
    onInvalidStep: (current) => goto(`/checkout/${current}`, { replaceState: true }),
  }));
</script>
  • Following the URL is a goTo. With linear, a deep link can only open the current step or one already completed. Without linear, any step can be opened, as with goTo.
  • The guard runs when the URL changes after the page is mounted. It does not run for the step the page first loads on.
  • onInvalidStep is called for unknown ids, for steps linear does not allow yet and for URL changes the guard refused.
  • On the server the flow starts on the URL's step when that is allowed, and no callback runs until the page is mounted.

A query parameter works the same way: read page.url.searchParams.get("step") and write it with goto.

Edit on GitHub

Last updated on