How to import components dynamically in React.js

Posted on January 26, 2021 in
1 min read

If you need to import a bunch of React.js components in a dynamic way, here the tip.

Let's assume you have a folder with a list of React.js components you want to include automatically at build time.

I'm also assuming you're using CRA scaffolding, or a Webpack based tooling.

Here the javascript that loads and creates an array of ready-to-use React.js components:

// look in a specific folder .js files
const requireComponent = require.context(

const list = []

requireComponent.keys().forEach((fileName) => {
  const componentConfig = requireComponent(fileName)
  const componentName = fileName
    .replace(/^\.\//, '')
    .replace(/\.\w+$/, '')
    .replace(/js/, '')

  const CompTag = componentConfig.default
    label: componentName,
    comp: <CompTag />

export default list

Now you can list the available components and render the selected one:

import { useState } from 'react'

import list from './utils/loadComponents.js'

function App () {
  const [comp, setComp] = useState(list.length - 1)
  const handleChange = (e) => {
    const index =

  return (
    <div className='app'>


      <select value={comp} onChange={handleChange}>
, i) => (
            <option key={d.label} value={i}>{d.label}</option>

export default App
Want to interact? Reach me out on Twitter
Spotted a typo? Send a patch