Skip to content

Instantly share code, notes, and snippets.

@YannisMarios
Last active June 16, 2022 03:58
Show Gist options
  • Save YannisMarios/7f3b947b46b4f79c06c79c2ff597eff0 to your computer and use it in GitHub Desktop.
Save YannisMarios/7f3b947b46b4f79c06c79c2ff597eff0 to your computer and use it in GitHub Desktop.
Dynamic loading of React components using a JSON config
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
import React from 'react'
const First = ({name, surname}) => {
return <div>{name} {surname}</div>
}
export default First
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