1

I get a JSON from an API, in which I find the links and names of components. These components I would like lazy load into my React application based on the information I received from the API call.

Example of the API response:

[
  {
    "path": "/path/to/app1",
    "linkName": "Component 1",
    "appName": "Component1",
    "importLink": "App1/Component1"
  },
  {
    "path": "/path/to/app2",
    "linkName": "Component 2",
    "appName": "Component2",
    "importLink": "App2/Component2"
  }
]

This is how I tried to loop over the data and lazy load the components assuming that in externalComponents is the stored API response:

const availableComponents = externalComponents.map((component: any) => {
  return { path: component.path, element: React.createElement(component.appName, {})};
});

availableComponents.forEach((component) => {
  const ComponentToLoad = React.lazy(() => import(component.importLink))
});

My question is how I can make the name of the const "ComponentToLoad" dynamic so that it uses the name of the component from the API (stored in "AppName" in the JSON) instead?

I also want to use the path from the API in react router. That's why I have 2 loops because I use the "availableComponents" in my router declaration like this:

const router = createBrowserRouter([
  {
    path: "/",
    element: <App />,
    errorElement: <ErrorPage />,
    children: availableComponents,
  },
]);

Is this the correct way to do this?

Any help would be much appreciated.

bbasmer
  • 127
  • 2
  • 11

0 Answers0