Home > Mobile >  React Router v6 add custom param into createBrowserRouter
React Router v6 add custom param into createBrowserRouter

Time:11-26

I need you help. I'm new in react router v6 so i need to add custom params in route object. But can't find any examples of it

 const AdminRoutes: FunctionComponent = () => {
      const router = createBrowserRouter([
        {
          path: '/',
          element: <Dashboard />,
          permission: ['edit'], //custom param
        },
      ]);
    
          return <RouterProvider router={router} />;
        };
        
  export default AdminRoutes;

   

Given Error -

Type '{ path: string; element: JSX.Element; permission: string[]; }' is not assignable to type 'RouteObject'.
  Object literal may only specify known properties, and 'permission' does not exist in type 'RouteObject'

Thanks for your help.

CodePudding user response:

You should be able to declare this object as a different type that extends RouteObject if you want to use it for other things as well.

type CustomRouteConfig = RouteObject & { permission: string[] }

const routeConfig: CustomRouteConfig[] = [{
  path: '/',
  element: <Dashboard />,
  permission: ['edit'], //custom param
}];

// note: you don't want to instantiate this router
// inside a functioncomponent body.
// at least stick it in a useEffect, but most likely
// this should be static.
const router = createBrowserRouter(routeConfig);

export const AdminRoutes: FunctionComponent = () => 
  <RouterProvider router={router} />
  • Related