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?

1

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the link to the official docs about it, missed that!
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 />;
}

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.