Selina
Selina

Reputation: 153

Dynamically adding components in react

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?

Upvotes: 2

Views: 6464

Answers (3)

Selina
Selina

Reputation: 153

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

Upvotes: 0

harrygogonis
harrygogonis

Reputation: 109

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 />;
}

Upvotes: 3

Anuj
Anuj

Reputation: 1474

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.

Upvotes: 7

Related Questions