TanStackT
TanStack2y ago
2 replies
verbal-lime

How to redirect from an intermediate route to a specific route?

Hey,
I have following routes:

/vouchers/creation/create
/vouchers/creation/output
/vouchers/creation/payment

If the user navigates to /vouchers/creation or /vouchers/creation/, I would like to redirect them immediately to /vouchers/creation/create. What is the best way to do this? The /vouchers/creation-component only shows at which step the user is located.

Here's my approach:

export const Route = new createFileRoute("/app/vouchers/creation")({
  beforeLoad: ({ location: { href } }) => {
    if (href.endsWith("/creation") || href.endsWith("/creation/")) {
      throw redirect({ to: "/app/vouchers/creation/create" });
    }
  },
  component: CreationComponent,
});


function Component() {
  const step = useRouterState({
    select: (s) => s.matches[s.matches.length - 1].routeContext.step,
  });

  const steps = [
    { name: "Create", active: step >= 1 },
    { name: "Output", active: step >= 2 },
    { name: "Pay", active: step >= 3 },
  ];

  return (
    <div className="flex flex-col">
      <ul className="steps mb-5 w-[28rem]">
        {steps.map((step, index) => (
          <li
            key={index}
            className={`step ${step.active ? "step-primary" : ""}`}
          >
            {step.name}
          </li>
        ))}
      </ul>
      <Outlet />
    </div>
  );
}

Thanks
Was this page helpful?