Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save SamanShafigh/a0fbc2483e75dc4d6f82ca534a6174d4 to your computer and use it in GitHub Desktop.
Save SamanShafigh/a0fbc2483e75dc4d6f82ca534a6174d4 to your computer and use it in GitHub Desktop.
React Component Dependency Injection (Dynamically loading components)
import React, { Component } from 'react';
import ComponentContainer from './ComponentContainer';
class App extends Component {
render() {
let components = ['D1', 'D2', 'D3'];
return (
<div>
<h2>Dynamic Components Loading</h2>
{components.map((componentId) => {
let Component = ComponentContainer[componentId];
return <Component>{componentId}</Component>;
})}
</div>
);
}
}
export default App;
import componentsConfig from 'ComponentsConfig';
let components = {};
for (var i = 0; i < componentsConfig.length; i++) {
let componentConfig = componentsConfig[i];
// Check if component is not already loaded then load it
if (components[componentConfig.name] === undefined) {
components[componentConfig.name] = require(`${componentConfig.path}`).default;
}
}
export default components;
export default [
{
name:'D1',
path:'D1'
},
{
name:'D2',
path:'D2'
},
{
name:'D3',
path:'D3'
}];
import React from 'react';
import D4 from './D4';
const D1 = ({children}) => {
return (
<div>
<D4>{children}</D4>
</div>
);
};
export default D1;
import React from 'react';
const D2 = ({children}) => {
return <div>{children}</div>
};
export default D2;
import React from 'react';
const D3 = ({children}) => {
return <div>{children}</div>
};
export default D3;
import React from 'react';
const D4 = ({children}) => {
return <div>{children}</div>
};
export default D4;
@SamanShafigh
Copy link
Author

This code provide an example of how we can dynamically load React components in another component and do a Dependency Injection

@hamed-farag
Copy link

Hello Saman,

Thanks a lot for your great Example, I just have a small issue, I tried to apply your concept in create-react-app v2 solution, and give me an error at this line

const layoutPath = mapping.layouts[mainLayout.name].path; // -> '../../layouts/ThreeColumns'
components[componentConfig.name] = require(`${componentConfig.path}`).default;

image

if i add the path like following it work normally,

components[componentConfig.name] = require('../../layouts/ThreeColumns').default;

do you have any idea about what happen ?

@Belphemur
Copy link

@hamed-farag Not the author and the question is old but don't use relative path ../../MyComponent for this.
Setup your react app to be sure to use absolute path ~/src/MyComponent (~ or @ depends on your settings)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment