Dynamic import with vite and react from a array loop

33 Views Asked by At

I want to use createBrowserRouter from react router dom but with dynamic imports. I want to save the url and filePath in an array and i want to loop through that array in createBrowswer router.

But it is not working When the pass the file path statically in the element in react lazy, it works, but when i pass the file path from the array while looping then it is not working.

I hope someone can help me in this issue or if there is a better way to do it.

This is working

import RootLayout from "@/pages/index.js";
import ProtectedLayout from "@/pages/protected/index.js";
import { createBrowserRouter } from "react-router-dom";
import { lazy } from "react";
export const routes: RouteType[] = [
{
filePath: "@auth/login",
path: routeConstants.auth.login,
},
{
filePath: "@protected/Dashboard",
path: routeConstants.dashboard.main,
},
];

const getRoutes = (routes: RouteType[]): any[] => {
let arr: any = [];
for (let i = 0; i < routes.length; i++) {
let current = routes[i];
let obj = {
path: current.path,
element: getComponent(current.filePath),
};

    arr = [obj, ...arr];

}
return arr;
};

const getComponent = (path: string) => {
const Component = lazy(() => import("@protected/Dashboard")); **//here is the change**
return <Component />;
};
export const router = createBrowserRouter([
{
element: <RootLayout />,
children: [
{
element: <ProtectedLayout />,
children: getRoutes(routes),
},
],
},
]);

This is not working

import RootLayout from "@/pages/index.js";
import ProtectedLayout from "@/pages/protected/index.js";
import { createBrowserRouter } from "react-router-dom";
import { lazy } from "react";
export const routes: RouteType[] = [
{
filePath: "@auth/login",
path: routeConstants.auth.login,
},
{
filePath: "@protected/Dashboard",
path: routeConstants.dashboard.main,
},
];

const getRoutes = (routes: RouteType[]): any[] => {
let arr: any = [];
for (let i = 0; i < routes.length; i++) {
let current = routes[i];
let obj = {
path: current.path,
element: getComponent(current.filePath),
};
    arr = [obj, ...arr];
}
return arr;
};

const getComponent = (path: string) => {
const Component = lazy(() => import(path)); **//here is the change**
return <Component />;
};
export const router = createBrowserRouter([
{
element: <RootLayout />,
children: [
{
element: <ProtectedLayout />,
children: getRoutes(routes),
},
],
},
]);
0

There are 0 best solutions below