75

I just can't find a way to set a default route with react-router v6

Is it because it's not good programming anymore?

Can somebody tell me why?

Thanks in advance

Rafael

9 Answers 9

116

If I understand your question about a "default" route correctly then I am interpreting this as one of the following:

  1. Use an index route:

    You can wrap a set of routes in a layout route and specify an index route:

<Routes>
  <Route path="/">
    <Route index element={<ComponentA />} />
    <Route path="pathA" element={<ComponentA />} />
    <Route path="pathB" element={<ComponentB />} />
    <Route path="pathC" element={<ComponentC />} />
  </Route>
</Routes>

or

<Routes>
  <Route path="/">
    <Route index element={<Navigate to="pathA" replace />} />
    <Route path="pathA" element={<ComponentA />} />
    <Route path="pathB" element={<ComponentB />} />
    <Route path="pathC" element={<ComponentC />} />
  </Route>
</Routes>

The index route is the route that will be matched and rendered when the path exactly matches the root parent route's path.

  1. Redirect to a "default" route if no other routes match:

    You can also render a redirect to the route you consider to be the "default" route.

<Routes>
  <Route path="/pathA" element={<ComponentA />} />
  <Route path="/pathB" element={<ComponentB />} />
  <Route path="/pathC" element={<ComponentC />} />
  <Route path="*" element={<Navigate to="pathA" replace />} />
</Routes>
9
  • 5
    Remember that, if you are using TypeScript. You need not to set path if you are setting index, otherwise you get Type 'true' is not assignable to type 'false | undefined' stackoverflow.com/questions/70708422/…
    – Andre Pena
    Commented Feb 22, 2022 at 20:57
  • 2
    @AndréPena I can't confirm if non-typescript users see any errors/warnings (trivial to test though), but it's not a valid use case to specify both the path prop and the index prop.
    – Drew Reese
    Commented Mar 1, 2022 at 9:09
  • can we set path for index route ?
    – Denny John
    Commented Apr 4, 2022 at 2:48
  • 1
    @DennyJohn The "path" for the index route is that of the parent layout route. In the first example above the nested index route will match on path "/". See more about index routes.
    – Drew Reese
    Commented Apr 4, 2022 at 17:47
  • 1
    @HarshvardhanSharma In that case you'd need to make a special component that can read any route params and redirect to any route with them injected into the new target path, or you just need to specify a default userid value, or default to a route that isn't so specialized.
    – Drew Reese
    Commented Nov 10, 2023 at 4:45
26

If you are using createBrowserRouter you can set the default route in following way.


const router = createBrowserRouter([
  {
    path: "/",
    element: <RootLayout />,
    children: [
      { index: true, element: <Navigate to="/calculation" replace /> },
      { path: "calculation", element: <Calculation /> },
      { path: "calendar", element: <Calendar /> },
      { path: "profile", element: <Profile /> },
    ],
  },
]);
4
  • 1
    Try to make your post looking more different from other existing posts. Using the exact same introduction line puts you at risk to be misread as copying an existing post. If you take the opportunity to edit and add more explanation to your noticably different code solution it would help a lot and probably get you closer to How to Answer.
    – Yunnosch
    Commented Feb 16, 2023 at 6:49
  • just looking for this! thanks! Commented Sep 7, 2023 at 14:01
  • Where does Navigate come from?
    – Dr.Random
    Commented Mar 26 at 13:31
  • 1
    Navigate is a component of 'react-router-dom' Commented Apr 29 at 2:21
19

TLDR;

use <Route index element={<Navigate to="/dashboard" />} />

index: default computed route.

<Navigate to="whatever you want"/>: is used to navigate to a another already declared path.

LR;

I found an easy way to redirect to a default component using index & Navigate combined.

In my situation I had used React Router V6.6.2 with:

createBrowserRouter(
    createRoutesFromElements(...))

The routes look like this

/* All imports go here */ 

const router = createBrowserRouter(
    createRoutesFromElements(
        <Route element={<AuthLayout />}>
            <Route element={<RrotectedLayout />}>
                <Route path="/" element={<MainLayout />}>
                    <Route index element={<Navigate to="/dashboard" />} />
                    <Route path="dashboard" element={<Dashboard />} />
                    <Route path="projects" element={<Projects />} />
                    <Route path="users" element={<Users />} />
                    <Route path="notifications" element={<Notification />} />
                    <Route path="settings" element={<Settings />} />
                    <Route
                        path="*"
                        element={<Navigate to="/dashboard" replace={true} />}
                    />
                </Route>
            </Route>
            <Route path="/signup" element={<Signup />} />
            <Route path="/login" element={<Login />} />
        </Route>,
    ),
    {},
)

export default function App() {
    return (
        <>
            <RouterProvider router={router} />
        </>
    )
}

Now when you access your application, React router will figure out which index your application needs to point to, and since your index contains a Navigation to a specific path, you'll be redirect to that path by default. you don't need to specify a specific component (element) in this situation because you don't wanna loose the link to it.

2
  • 1
    <Navigate> was just was I was looking for! <Routes> <Route path="/" index element={<Navigate to="page/:id" />} /> <Route path="page/:id" element={<MainScreen />} /> </Routes>
    – gwar9
    Commented Feb 10, 2023 at 18:42
  • 1
    Just adding as an FYI for anyone seeing a "max depth" error, path="*" can do that, try using a specific path instead. Commented Mar 22, 2023 at 5:19
3

If you are using createBrowserRouter you can set the default route in following way.

As per docs component loads children of parent. So

const router = createBrowserRouter([
  {
    path: "/",
    element: <App />,
    children: [
      {
        path: "/",
        element: <Home />,
      },
      {
        path: "/home",
        element: <Home />,
      },
    ],
  },
],);
1

Here is my working solution using "createBrowserRouter":

    const router = createBrowserRouter([
        {
          path: "/",
          element: (
            <Root />
          ),
          children: [
            {
              path: "/",
              element: <Navigate to={"/" + pageIds.home} replace={true} />,
                }, 
            {
              path: pageIds.home,
              element: (<Homepage />),
            },
          ]
        },
    ]);

The reason I use the "Navigate" component is so that I'm not duplicating my use of the "Homepage" component, which has a lot of parameters (not shown here).

1
  • Thanks a lot. I have more updates for it { path: '*', element: <Navigate to={'/home'} replace={true} />, }, { path: '', element: <Navigate to={'/home'} replace={true} />, } Commented May 10 at 10:20
0

I actually found the answer here but I just wanna share my solution if it helps someone with theirs.

You can set path='*' to make a default route. The index route deals a parent route ("/") but doesn't deal with routes which should otherwise return a 404 status.

if (!token) {
    // This router will handle my public routes. Anything else is going to redirect to AuthPage without losing the previous route typed.
    return (
      <BrowserRouter>
        <Routes>
          {/* Auth  */}
          <Route path="/">
            <Route exact path="recover" element={<UnknownPage />} />
            // Default route
            <Route path="*" element={<AuthPage setToken={setToken} />} />
          </Route>
        </Routes>
      </BrowserRouter>
    );
  }

  // This router is inside my application. Only logged users will get here.
  return (
    <BrowserRouter>
      <Routes>
        {/* My base page is just some fixed structure like Header, Sidebar and Footer. For this problem you can ignore it. */}
        {/* BasePage  */}
        <Route path="/*" element={<BasePage logout={logout} />}>
          {/* This is my specific users route */ }
          {/* Users */}
          <Route path="users">
            <Route path="" element={<UsersPage />} />
            <Route path=":id" element={<UserInfoPage />} />
          </Route>

          {/* Anything else is going to show this page. Even random words like:  http:localhost:3000/anything-asdvasd */}
          {/* Default Route */}
          <Route path="*" element={<UnknownPage />} />
        </Route>
      </Routes>
    </BrowserRouter>
  );

Using parent routes like I used in my users routes makes it easier to scope your default routes.

0
0

You can make the path a variable like this:

      <Route path=':default' Component={LandingPage2}></Route>
0

You can use this code snippet below: the default child element path set to emptyString "" becomes the default route.

 import { createBrowserRouter,RouterProvider } from "react-router-dom";
    
    class App extends React.Component {
        constructor(props){
            super(props);
            this.state = {
                yourObject: null
            };
        }
        router = createBrowserRouter([
            {path: "/", children: [ 
                {path:"", element: <Default/>},
                {path:"pathA", element: <ComponentA/>},
                {path:"pathB",  element: <ComponentB/> },
                {path:"pathC",  element: <ComponentC /> }
           ]}]);
        render() { return ( <RouterProvider router={this.router} /> ) }
    }
0

If you want the user to navigate to start component from / then use this.

Ex: website is www.mywebsite.com and you want your users to be directed to the start pages component.

// main.tsx

import React from 'react'
import ReactDOM from 'react-dom/client'
import {
  createBrowserRouter,
  RouterProvider,
} from "react-router-dom";
..other imports..

const router = createBrowserRouter([
  {
    path: "react-bootstrap/",
    element: <Root />,
    errorElement: <ErrorPage />,
    children: [
      {
        path: "home",
        element: <Home />,
      },
      {
        path: "", // this right here
        element: <Home />,
      },
      {
        path: "about",
        element: <About />,
      },
      {
        path: "contacts",
        element: <Contact />,
      },
    ],
  },
]);

ReactDOM.createRoot(document.getElementById("root")!).render(
  <React.StrictMode>
    <RouterProvider router={router} />
  </React.StrictMode>
)

Reason for this is because Im rendering the component inside with a fixed <Header/> and </Footer> components.

Not the answer you're looking for? Browse other questions tagged or ask your own question.