Search code examples
react-router

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


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


Solution

  • 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.

    2. 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>