In React Router v6, how do I get the route object?

Viewed 26

Below, I have a routes object. How do I pull the actual route object for evaluation? I know how to get the pathname. As you can see in my Routes object, I have added some additional information to use in various places. I can iterate the object, but I was hoping for a more built in solution. Another solution is create my own object and supply it to this object, but that feels redundant to me. Thanks in advance.

export const Routes = [
  {
    path: '/',
    element: <Root />,
    errorElement: <ErrorPage />,
    children: [
      {
        path: '/',
        element: <Home />,
        name: 'Home',
        topBar: false,
      },
      {
        path: 'projects',
        element: <Projects />,
        errorElement: <ErrorPage />,
        name: 'Projects',
        topBar: true,
        children: [
          {
            path: 'bst',
            element: <Bst />,
            name: 'BST Visualizer',
            sideBar: true,
          },
          {
            path: 'knightstour',
            element: <KnightsTour />,
            name: "Knight's Tour",
            sideBar: true,
          },
        ],
      },
      {
        path: 'blog',
        element: <Blog />,
        name: 'Blog',
        topBar: true,
      },
      {
        path: 'contact',
        element: <Contact />,
        name: 'Contact',
        topBar: true,
      },
    ],
  },
]
1 Answers

I would suggest to use the loader function to provide data to the Route element.
With useLoaderData, you will be able to retrieve the data.

const router = createBrowserRouter([
  {
    path: '/',
    element: <Home />,
    loader: () => ({
      name: "Home", 
      topBar: true
    })
  },
  ...
]);

function Home() {
  const { name, topBar } = useLoaderData();
  return <p>Name = {name}</p>;
}

Here is an example on Stackblitz

Related