is there a way to set a default route with React-Router v6

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="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>

Leave a Comment