In React Router v6, you can now include a custom parameter in createBrowserRouter

Hey there! I'm currently diving into react router v6 and struggling to add custom params in the route object. Unfortunately, I haven't been able to find any examples of how to do it.

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

   

Encountered 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'

Your assistance is greatly appreciated.

Answer №1

To enhance the traditional RRD approach, I recommend creating a route component that incorporates an additional parameter as a prop and manages the functionality accordingly.

For instance:

const PermissionLayout = ({ permission }) => {
  const hasPermission = ... permission logic ...

  return hasPermission ? <Outlet /> : <Navigate to="/" replace />;
};
const router = createBrowserRouter([
  {
    element: <PermissionLayout permission={['edit']} />
    children: [
      {
        path: "/",
        element: <Dashboard />,
      }
    ],
  },
  ...
]);

const AdminRoutes: FunctionComponent = () => {
  return <RouterProvider router={router} />;
};
        
export default AdminRoutes;

Answer №2

If you wish to utilize this object for various purposes, consider declaring it as a different type that is an extension of RouteObject.

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

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

// Remember not to create the router instance within a function component body.
// It's best to place it in a useEffect hook or make it static instead.
const router = createBrowserRouter(routeConfig);

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

Answer №3

import React from 'react';
import i18next from 'i18next';
import '../internationalization/i18next';
import {
  Navigate,
  IndexRouteObject,
  NonIndexRouteObject,
  createBrowserRouter,
} from 'react-router-dom';
import { LayoutAuth } from '../components';
import { SignIn } from '../containers';

type CustomRouteObjectParams = {
    category?: 'authorization' | 'administration';
    title?: string;
};

type CustomIndexRouteObject = IndexRouteObject & CustomRouteObjectParams;

type CustomNonIndexRouteObject = Omit<NonIndexRouteObject, 'children'> &
    CustomRouteObjectParams & {
        children?: (CustomIndexRouteObject | CustomNonIndexRouteObject)[];
    };

type CustomRouteConfig = CustomIndexRouteObject | CustomNonIndexRouteObject;

export const routes: CustomRouteConfig[] = [{
    path: '/auth',
    category: 'authorization',
    title: i18next.t('routes:auth'),
    element: <LayoutAuth />,
    children: [
        {
          index: true,
          element: <Navigate to="signin" />,
        },
        {
          path: '*',
          element: <Navigate to="signin" />,
        },
        {
          path: 'signin',
          title: i18next.t('routes:signin'),
          element: <SignIn />,
        },
      ],
}]

export const router = createBrowserRouter(routes);

export type TRoutes = typeof routes;

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue with arrow function not being invoked in a React TypeScript component's prop inside a function

My parent component holds a useState hook to determine if the mobile Nav is open or closed: const [showMobileMenu,setShowMobileMenu] = useState<boolean>(false);. To close the mobile menu, I created an arrow function and passed it down to a child comp ...

Remove the underline from links in gatsbyjs

When comparing the links on (check source code https://github.com/gatsbyjs/gatsby/tree/master/examples/using-remark), they appear without an underline. However, on my blog (source code here: https://github.com/YikSanChan/yiksanchan.com), all links are un ...

Error in Ionic Cordova Build prod: Module "." not found - Requires Typescript version >3

After updating my ionic project and all dependencies, I encountered an error when trying to build a --prod android apk: Uncaught Error: Cannot find module "." at vendor.js:1 at vendor.js:1 at Object.<anonymous> (vendor.js:1) at e (vendor.js:1) at Ob ...

React Native ScrollView with a custom footer that adjusts its size based on the content inside (

I've implemented the code below to ensure that the blue area in image 1 remains non-scrollable when there is sufficient space, but becomes scrollable when space is limited. However, I'm facing an issue where the ScrollView component is adding ext ...

What is the best way to implement multiple templates for a single component?

Is there a way to configure my Home Component based on the user's role? For instance: If the employee is an admin, then the home component should load the template URL designed for admins. Likewise, if the employee is a cashier, then the home compo ...

Extract CSS from Chrome developer tools and convert it into a JavaScript object

Recently, we have started incorporating styles into our React components using the makeStyles hook from Material-UI. Instead of traditional CSS, we are now using JavaScript objects to define styles. An example of this is shown below: const useStyles = ma ...

When attempting to access front-end SPA links through the browser, the back-end triggers an error due to not being

My front-end single-page-application is built using JS (ReactJS), and the back-end is running on Phoenix (Elixir). Everything functions smoothly within the application, but I encounter a route error from Phoenix when attempting to access a page in the SPA ...

Exploring the functionality of window.matchmedia in React while incorporating Typescript

Recently, I have been working on implementing a dark mode toggle switch in React Typescript. In the past, I successfully built one using plain JavaScript along with useState and window.matchmedia('(prefers-color-scheme dark)').matches. However, w ...

There was an error encountered: TypeError - show.visible cannot be iterated upon. This issue might be related to

I am facing an issue while using React's functional component to update the state. My intention was to fetch data and display the first 10 items, followed by a "load more" button which would reveal another set of 10 items upon clicking. Can someone as ...

Using nested ternary operations in React can cause issues with accessing local variables

Note: I encountered an issue where the extra curly braces around the first ternary result did not solve my initial problem. I replaced them with parentheses. Josep's suggestion to use getTime required me to equate the dates. The Date().setHours(0, 0, ...

Converting a CodePen JavaScript file into a React application involves adapting the code structure to fit the React framework and incorporating necessary dependencies

Exploring the functionality of the FilePond module within a React application by uploading a basic file is something I am eager to showcase. To see an example, I have prepared a CodePen demonstration: https://codepen.io/rikschennink/pen/WXavEx If you nav ...

What is the best way to customize the renderItem method in React Native's SectionList to be based on sections instead of

I've been exploring the FB docs and came across a mention of being able to override the default item-based renderItem method with a section-based render in the SectionList component in React Native. However, I'm struggling to find a way to actual ...

What is the best way to display the source code of a function in TypeScript?

I am interested in obtaining the source code for my TypeScript function ** written in TypeScript **. Here is the TypeScript code: var fn = function (a:number, b:number) { return a + b; }; console.log("Code: " + fn); This code snippet displays the Ja ...

Angular: Understanding the intricacies of HTTP calls in ngOnInit versus click events (potentially related to caching mechanisms)

Within my Angular application, I have a basic service configured to communicate with the server. The service has been injected into a component. Interestingly, when I directly call one of its methods inside the ngOnInit() method of the component, everythin ...

Troubleshooting tips for resolving issues when launching Nx React + Express

[webpack-dev-server] [HPM] Encountered an issue while forwarding request localhost:4200/api to http://localhost:3333/ [ECONNREFUSED] (https://nodejs.org/api/errors.html#errors_common_system_errors) While setting up my nx app with react and express, I face ...

Restrictions on pairings of kind variables within generic utilization

Currently, I am creating a declaration file for a library called chart.js. The process of constructing a new chart involves the following: let chart = new Chart(ctx, { type: 'line', data: ..., options: ... }) The types of the data and options f ...

Out of the blue, the CSS functionality in my React app completely ceased to

I've been developing this website using React and Material UI, and I chose to implement standard CSS for styling. However, after closing my code editor and reopening it, some parts of the CSS do not seem to be loading properly. I'm completely puz ...

What is the solution for resolving the SyntaxError with `...theme.mixins` in your code?

I am currently utilizing material-ui version 1.3.1 along with reactjs 16.4.1. After incorporating the PaperSheet Component from their official website into my project, I encountered a complication where my application no longer compiles successfully. What ...

Unable to successfully retrieve a PDF file (stored as binary data) from Mongo-db using React JS technology

I integrated the express-fileupload library for uploading a PDF file to MongoDB, but I am encountering an issue while trying to download the same file on the front end. Upon downloading the PDF, I receive the following error message: "Error. Failed t ...

The promise chain from the ngbModal.open function is being bypassed

I'm currently working on implementing data editing within a component. My task involves checking if any of the data fields have been altered, and if so, prompting a confirmation pop-up to appear. If the user confirms the change, the data will then be ...