How do I set a route as an Index if it requires a parameter

Viewed 40

I was following the quick start guide on react-router, and I came across this code sample that shows how to direct a route to a nested route by default using index.

Now my question is if the path you're trying to switch to requires a parameter :someID how would I set it as the index with a default value? e.g /23

function App() {
  return (
    <Routes>
      <Route path="/" element={<Layout />}>
        <Route index element={<Activity />} />
        <Route path="invoices" element={<Invoices />} />
        <Route path="activity" element={<Activity />} />
        <Route path=":someID" element={<SomePath />} />
      </Route>
    </Routes>
  );
}
1 Answers

If I'm understanding your question correctly now, you are asking how to default your app to a specific URL path. For this you can render a redirect to the "/:category" route with some default value, i.e. <Route path="*" element={<Navigate to="/defaultCategory" replace />} /> when the app mounts and the URL path isn't already a match for the category route.

Example:

import { Routes, Route, Navigate } from 'react-router-dom';

...

<Routes>
  <Route path="/:category" element={<Main />} />
  <Route path="*" element={<Navigate to="/foo" replace />} />
</Routes>

Another method would be to have the App component issue an imperative redirect to a default category value. This requires App to have a router higher than it in the ReactTree so App can access the routing context it provides.

Example:

import { Routes, Route, useNavigate } from 'react-router-dom';

const App = () => {

  const navigate = useNavigate();

  useEffect(() => {
    // redirect to default category when `App` mounts
    navigate("/foo", { replace: true });
  }, []);

  return (
    ...

    <Routes>
      <Route path="/:category" element={<Main />} />
    </Routes>

    ...
  );
}

...

<BrowserRouter>
  <App />
</BrowserRouter>
Related