Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use an index route with useRoutes in React Router 6

Tags:

react-router

<Route path="/exercises" element={<Layout />}>
  <Route index element={<List />} />
  <Route path=":id" element={<Exercise />} />
</Route>

How would I rewrite this as JS objects for useRoutes() including the index route?

{
    path: "/exercises",
    element: <Layout />,
    children : [
      {index? , element: <List />},
      {path: ":id", element: <Exercise /> }
 ] 
}

I'm not sure what to do with index...


2 Answers

The useRoutes hook takes an array of RouteObject objects

/**
 * A route object represents a logical route, with (optionally) its child
 * routes organized in a tree-like structure.
 */
export interface RouteObject {
  caseSensitive?: boolean;
  children?: RouteObject[];
  element?: React.ReactNode;
  index?: boolean;
  path?: string;
}

You should be able to specify what is an index route using the index property.

{
  path: "/exercises",
  element: <Layout />,
  children: [
    { index: true, element: <List /> },
    { path: ":id", element: <Exercise /> }
  ],
}
like image 158
Drew Reese Avatar answered Oct 22 '25 05:10

Drew Reese


This seems to work:

{
    path: "/exercises",
    element: <Layout />,
    children : [
      {path: "" , element: <List />},
      {path: ":id", element: <Exercise /> }
 ] 
}

When the path is /exercises Layout is Rendered and List is rendered in the Outlet in Layout. when the path is /exercises/4 (for example) the Exercise component is rendered in Outlet in Layout.