React: dynamic jsx import

This question is related to the dynamic import of JSX files into React.

Basically, we have one main component that dynamically displays other components based on the structure stored in the database. Dynamic components are stored in the subdirectory "./Components". We statically define this as:

import CompA from './Components/CompA'; import CompB from './Components/CompB'; var components = { 'CompA': CompA, 'CompB': CompB } 

and we visualize them using:

 var type = 'CompA' var Component = components[type]; ... <Component /> 

While this works just fine, for us it's too static. We have another 100 components (CompA / CompBs), and their static definition does not work.

Can I import all JSX files into "./Compontents" and populate the component array?

And that would be really (really) nice if we could send the "./Components" path as a support for the main components. And the main component will use this path to import .jsx files. Like this:

 <MainComponent ComponentPath="./SystemComponents"> 

Uses "./SystemComponents" as the path to .JSX files and:

 <MainComponent ComponentPath="./UserComponents"> 

Use "./UserComponents" as the import path.

+6
source share
2 answers

Regarding the presence of /index.js components with content:

 export CompA from "./comp_a"; export CompB from "./comp_b"; 

Then follow these steps:

 import * as Components from "./components" 

then you will use as:

 <Components.CompA /> <Components.CompB /> ... 

Hope this helps.

I doubt that you can load anything when sending a path through component details, then the file should be loaded inside the React component life cycle methods, which I would not recommend.

+8
source

To add a comment @ gor181, I can add that export should be as follows:

export { default as CompA } from "./comp_a"; export { default as CompB } from "./comp_b";

Hope this can be helpful.

0
source

All Articles