Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React: dynamic import jsx

Tags:

reactjs

This question related to dynamically importing JSX files into React.

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

import CompA  from './Components/CompA';
import CompB  from './Components/CompB';

var components = {
 'CompA': CompA,
 'CompB': CompB
}

and we render them using:

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

While this works fine, it is a bit too static for us. We have 100+ components (CompA/CompBs) and statically define them does not work.

Is it possible to import all JSX files in "./Compontents" and populate the components-array?

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

<MainComponent ComponentPath="./SystemComponents">

Would use "./SystemComponents" as path for .JSX files and:

<MainComponent ComponentPath="./UserComponents">

Would use "./UserComponents" as import path.

like image 779
mathan Avatar asked Apr 17 '16 14:04

mathan


1 Answers

What about having a components/index.js with contents:

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

Then you do:

import * as Components from "./components"

then you would use as:

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

Hope this helps.

I doubt you can load anything when sending path through component props, loading of the file should then happen inside the React component lifecycle methods which is not something I would recommend.

like image 86
gor181 Avatar answered Sep 21 '22 23:09

gor181