Suppose that you have an array of objects containing the component name in string like below

[{
    "component":"Test",
    "path":"./Test"
}]

Now you want to iterate over this array, get the component name and require the component which matches with the name.

You would normally inject the components at compile time. You would import the components from your local path put that in curly braces,but here we want to get the component dynamically if it matches with the name and inject it.

We would do two things in order to do that

  • first is to require the component dynamically using require command
  • then we would use the react.createElement to create the react element.

Here is the code

app.json

[{
    "component":"Test",
    "path":"./Test"
}]

JS file

import React, { Component } from 'react';
import config from './app.json';

class App extends Component {
 render() {
   return (
       {
         // Iterate
         config.map((obj)=>{
           // Require and compile element
           let component = require(`${obj.path}`).default
           component = React.createElement(component);
           return component
         })
       }
     </div>
   );
 }
}

export default App;