Skip to content

Instantly share code, notes, and snippets.

@davidgljay
Last active June 12, 2022 19:22
Show Gist options
  • Star 52 You must be signed in to star a gist
  • Fork 9 You must be signed in to fork a gist
  • Save davidgljay/5d7a29c5add8b360b93db838235e80a8 to your computer and use it in GitHub Desktop.
Save davidgljay/5d7a29c5add8b360b93db838235e80a8 to your computer and use it in GitHub Desktop.
Pattern for dynamically loading React components based on a config json object.
import config from '../config'
let components = {}
//For each component in the config fiel into an object
for (var i = config.length - 1; i >= 0; i--) {
components[config[i].name] = require(config[i].path).default
}
export default components
/* Alternative if this require business makes you too queasy */
// import First from './First'
// import Second from './Second'
// import Third from './Third'
// export const First = First
// export const Second = Second
// export const Third = Third
export default [
{
name:'First',
path:'./First'
},
{
name:'Second',
path:'./Second'
},
{
name:'Third',
path:'./Third'
}]
import React from 'react';
//Example components, keeping these super simple
class First extends React.Component {
render() {
return <h1>First</h1>
}
}
export default First
import React from 'react';
import Components from './ComponentIndex'
import config from '../config'
class AppComponent extends React.Component {
render() {
return (
<div className="index">
<h2>Component structure test</h2>
{config.map((comp) => {
/*Load each component in the config file in order.
* Note that the config object could also include props
* which could be passed in like so:
* <Component {..config.props} />
*/
if (Components.hasOwnProperty(comp.name)) {
let Component = Components[comp.name];
return <Component key={comp.name} />
}
})}
</div>
);
}
}
export default AppComponent;
import React from 'react';
class Second extends React.Component {
render() {
return <h1>Second</h1>
}
}
export default Second
import React from 'react';
class Third extends React.Component {
render() {
return <h1>Third</h1>
}
}
export default Third
@davidgljay
Copy link
Author

Overview

This is a pattern for dynamically loading react components based on a configuration object.

Motivation

Projects like Playground include many possible components that a user can choose to add or remove. We could put each of these components behind an if statement, but this would become burdensome as the number of components expands and as we think about supporting third party plugins. The pattern above will let us dynamically determine which components are loaded either based on a JSON object (when loading a configuration from the server) or based on props.

Pros

  • Allows us to load a new component by updating only the config object and package.json files.
  • Simplifies code like Playground, where there are many optional display components.
  • Generally lets us rearrange application structure by rearranging application state.

Cons

  • Breaks the principle behind a react pattern (don't pass components in props)
  • Placing application structure in config or store may make code less readable

@mk48
Copy link

mk48 commented Aug 9, 2017

Thanks lot, it really helped me. 👍

@caype
Copy link

caype commented Sep 5, 2017

This was really helpful. I had to dynamically render user selected components in a dashboard.
Thanks a lot :)

@xs9627
Copy link

xs9627 commented Sep 19, 2017

Sorry, I'm new to React. But does this line of code works?
require(config[i].path).default

When I use variable in 'require', it get following error
Error: Cannot find module "."

Searched in Google, the dynamic require seems not supported yet.
According to:
https://stackoverflow.com/questions/38374344/require-file-with-a-variable-in-react-js
facebook/metro#52

Correct me If I'm wrong. Thanks!

@lineldcosta
Copy link

Even i am getting the same error Error: Cannot find module "."

@adityan-webonise
Copy link

Just to be clear, lets not get confused between two different things. The snippet is to dynamically load the React Component and not the javascript files. The files are expected to be already loaded.

You can refer maybe this to get the files loaded dynamically going (not tried).

@afternoon2
Copy link

afternoon2 commented Jun 5, 2018

What worked for me was the piece of code below. It uses async module import. Please note that dynamic import() still has some caveats like not accepting expressions as parameters. Only pure strings or template literals.

Using the example from the gist at the top:

import config from '../config'

let components = {}

function registerComponent(entry) {
    import(`some/root/path/${entry.id}`) // just entry.path won't work :(
        .then(component => components[entry.name] = component.default)
        .catch(error => console.log(error))
}

function addComponents(configArr) {
    configArr.forEach(async entry => {
        await registerComponent(entry)
    })
}

addComponents(config)

export default components

@shinuvs
Copy link

shinuvs commented Aug 10, 2018

Hi, how to use this for React native

@gowthamans268
Copy link

I receiving some error like Invalid call at line 17: import("." + entry.path) // just entry.path won't work

@gowthamans268
Copy link

What worked for me was the piece of code below. It uses async module import. Please note that dynamic import() still has some caveats like not accepting expressions as parameters. Only pure strings or template literals.

Using the example from the gist at the top:

import config from '../config'

let components = {}

function registerComponent(entry) {
    import(`some/root/path/${entry.id}`) // just entry.path won't work :(
        .then(component => components[entry.name] = component.default)
        .catch(error => console.log(error))
}

function addComponents(configArr) {
    configArr.forEach(async entry => {
        await registerComponent(entry)
    })
}

addComponents(config)

export default components
```Invalid call at line 17: import("." + entry.path) // just entry.path won't work

@YannisMarios
Copy link

This worked for me:
https://gist.github.com/YannisMarios/7f3b947b46b4f79c06c79c2ff597eff0

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

@kristoff2016
Copy link

Hello there,
Thank you for sharing. does it work for share props to child First.js with componentWillReceiveProps ?

Thank you

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