Search code examples
javascriptreactjsreact-routerreact-router-dom

How to set default route parameter value in react router?


I want to prevent additional redirect. Is there a way to set default parameter value in router config?

export const router = createBrowserRouter([
  {
    path: '/admin',
    element: <App/>,
    errorElement: <PageError/>,
    children: [
      {
        index: true,
        path: 'schedule/:date?',
        element: <React.Suspense fallback={<Loading />}>
          <PageCalendar />
        </React.Suspense>,
      },

Basically I want "/admin/schedule/2023-05-11" (current date) page to open if user tries to open "/admin" or "/admin/schedule" page.


Solution

  • I don't believe there's a way to accomplish this without a redirect somewhere to get the UI synchronized with the correct URL path in the browser.

    You can include a "catch-all" route that injects the current date and redirects to the default route.

    Example:

    import { Navigate, generatePath } from 'react-router-dom';
    
    const ScheduleRedirect = () => {
      const date = /* compute formatted date, e.g. "2023-05-11" */
      return (
        <Navigate
          to={generatePath("/admin/schedule/:date", { date })}
          replace
        />
      );
    };
    
    export const router = createBrowserRouter([
      {
        path: '/admin',
        element: <App/>,
        errorElement: <PageError/>,
        children: [
          {
            path: 'schedule/:date',
            element: (
              <React.Suspense fallback={<Loading />}>
                <PageCalendar />
              </React.Suspense>
            ),
          },
        ],
      },
      {
        path: "*",
        element: <ScheduleRedirect />,
      },
    ]);