Last active
June 16, 2022 03:58
-
-
Save YannisMarios/7f3b947b46b4f79c06c79c2ff597eff0 to your computer and use it in GitHub Desktop.
Dynamic loading of React components using a JSON config
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { lazy, Suspense } from 'react' | |
import Spinner from '../../ui/spinner/Spinner' // Some Spinner | |
const config = [ | |
{ | |
name: 'First', | |
path: './First', | |
props: {name: 'Yannis', surname: 'Marios'} | |
}, | |
{ | |
name: 'Second', | |
path: './Second', | |
props: {name: 'John', surname: 'Doe'} | |
} | |
] | |
const importedComponents = () => { | |
const components = {} | |
for(let i = 0; i < config.length; i++) { | |
components[config[i].name] = lazy(() => import(`${config[i].path}`)) | |
} | |
return components | |
} | |
const DynamicComponents = () => { | |
const Components = importedComponents() | |
const components = config.map(c => { | |
const Component = Components[c.name] | |
return <Suspense key={c.name} fallback={<Spinner/>}><Component key={c.name} {...c.props} /></Suspense> | |
}) | |
return <div>{components}</div> | |
} | |
export default DynamicComponents |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from 'react' | |
const First = ({name, surname}) => { | |
return <div>{name} {surname}</div> | |
} | |
export default First |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from 'react' | |
const Second = ({name, surname}) => { | |
return <div>{name} {surname}</div> | |
} | |
export default Second |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment