reactjsreact-routerlazy-loadingreact-suspensereact-location

How to lazy load route with react location?


I am quite new to React, and I have a project that uses react-location

I would like to load some routes lazily only if the path is activated.

My current config is:

my base routing module

export const routes: Route[] = [
  ...HomeModuleRoutes, // I want this to be instantly loaded.
  ...LazyRoutes, // I want this to be lazy loaded.
  { path: '/', element: <Navigate to="/home" /> },
];

those 2 constants look like this :

home.routing.ts

export const routes: Route[] = [
  {
    path: 'home',
    element: <HomeTemplate />,
    children: [
      {
        path: '/',
        element: <HomePage />,
      },
    ],
  },
];

lazy.routing.ts

export const LazyRoutes: Route[] = [
  {
    path: 'test',
    element: <LazyTemplate />,
    children: [
      {
        path: '/',
        element: <LazyList />,
      },
      {
        path: 'add',
        element: <LazyAdd />,
      },
      {
        path: 'detail',
        element: <LazyDetail />,
      },
    ],
  },
];

I don't quite see documentation or an example on this, is it just wrapping the component with <Suspense>?


Solution

  • You should import your component with React.lazy like:

    const HomeTemplate = React.lazy(() => import("./HomeTemplate "));
    

    check this example for react-router v6 lazy loading