React - Dynamically Import Components React - Dynamically Import Components javascript javascript

React - Dynamically Import Components


I think there may have been some confusion as to what I was trying to achieve. I managed to solve the issue I was having and have shown my code below which shows how I solved it.

Separate File (ComponentIndex.js):

    let Components = {};    Components['Component1'] = require('./Component1').default;    Components['Component2'] = require('./Component2').default;    Components['Component3'] = require('./Component3').default;    export default Components

Main File (Main.js):

    import React, { Component } from 'react';    import Components from './ComponentIndex';    class Main extends Component {        render () {            var type = 'Component1'; // example variable - will change from user input            const ComponentToRender = Components[type];            return <ComponentToRender/>        }    }    export default Main

This method allows me to add/remove components very quickly as the imports are in one file and only requires changing one line at a time.


Since the question is really old, the answers maybe were ok. But nowadays, if someone have the same problem should use dynamic import, in order to load only the component needed and avoid to load all the different ones.

const component = React.lazy(() => import('./component.jsx'));

try the example here: demo


import React, { Component } from 'react'import Component1 from './Component1'import Component2 from './Component2'import Component3 from './Component3'class Main extends Component {    render() {        var type = 'Component1';  // just an example        return (          <div>            {type == "Component1" && <Component1 />}            {type == "Component2" && <Component2 />}            ...          </div>        )    }}export default Main

You can use conditional rendering insted. Hope it will help

Check this