ReactJs - Independent Component and Dynamic IMport/Usage


(Retromime) #1

ell me If something like this is possible in ReactJs.

IDEA: To allow other developer to write his own component to include in a Root application without modify the Root itself, I was thinking something like this:

The developer write a React Component (a single Jsx with eventually a config.json) and put it in a specific directory. Some mandatory rules will be applied like ComponentName === filename etc…;

During building, webpack will reads the directory where developers will put their own components and exposes the name of them in a global variable (for example in process.env);

Now I will have an array of component’s name like this:

gadgets = [ "HelloWorld" , "FarewellWorld" ]

This is the idea of filesystem organization:

├── gadgets
│   ├── module_name
│   │   ├── FarewellWorld
│   │   │   └── FarewellWorld.jsx
│   │   └── HelloWorld
│   │       └── HelloWorld.jsx
│   └── other_module
├── HomePage.jsx

In my HomePage.jsx I want to import the components and use them without modify the file itself so after re-build the new component appears magically in the page. The original idea was something like this:
Some magic wildcards import:

import * from './gadgets/module_name/*/'

renderAllGadgets()
{
    let allGadgets = [];
    process.env.gadgets.map(function(gadget){
      allGadgets.push(React.createElement(gadget,{});
    }
    return allGadgets;
}

 render() {
        return <div>
                 { this.renderAllGadgets() }
               </div>
 }

I know the code above is more close to ScyFy, but thinking as proof of concept, is this approach possible?

Thanks you.