2

I need to add components by rendering it in react:

<componentName ..... />

However, the name of component is not known and coming from a variable. How I can render that?

cs95
  • 379,657
  • 97
  • 704
  • 746
Selina
  • 153
  • 3
  • 14
  • Refer to this answer https://stackoverflow.com/questions/36941829/how-to-load-component-dynamically-in-reactjs/46188808#46188808 – Saman Sep 15 '17 at 05:26

3 Answers3

7

You will need to store references to the dynamic components:

import ComponentName from 'component-name'

class App extends Component {
    constructor(props) {
        super(props)

        this.components = {
            'dynamic-component': ComponentName
        }
    }

    render() {
      // notice capitalization of the variable - this is important!
      const Name = this.components[this.props.componentName];

      return (
        <div>
          <Name />
        </div>
      )
    }
};

render(<App componentName={ 'dynamic-component' } />, document.getElementById('root'));

See the react docs for more info.

Anuj
  • 1,474
  • 12
  • 23
3

You can create a file that exports all the different components

// Components.js
export Foo from './Foo'
export Bar from './Bar'

then import them all

import * as Components from './Components'

then you can dynamically create them based on a variable/prop:

render() {
  // this.props.type = 'Foo'
  // renders a Foo component
  const Component = Components[this.props.type];
  return Component && <Component />;
}
harrygogonis
  • 109
  • 3
0
Okay, for me this worked:

import {Hello} from 'ui-hello-world';

let components = {};

components['Hello'] = Hello;
export default components;

and then in my class: import customComps from '.....json'; .... let Component = Custom.default[customComps.componentName];

      return (
        <Component
Selina
  • 153
  • 3
  • 14