Render a React component based on its name

Context: I am developing a widget-based webapp, (like the defunct iGoogle, where users can choose which widgets they want to display). Each widget is a React component.

Simplified example:
Here are 2 different widgets

var HelloWidget = React.createClass({
    render: function() { return <div>Hello {this.props.name}</div>; }
});

var HiWidget = React.createClass({
    render: function() {  return <div>Hi {this.props.name}</div>; }
});

As a user, I have chosen the HiWidget and my name is “dude” so when the system gets my preferences from the persistence layer it looks like this:
var dataFromDb = {
    type: 'HiWidget',
    name: 'dude'
};

How can I render a React component when I have its name in a string var ?

I tried this, based on Dynamically Rendering a React component :

React.render(
  <dataFromDb.type name={dataFromDb.name} />,
  document.getElementById('try2')
);

It used to work with React 0.11, but not anymore.

And I would like to avoid having a giant switch statement:

switch (dataFromDb.type) {
    case 'HiWidget':
        var component = <HiWidget name={dataFromDb.name} />;
        break;
    case 'HelloWidget':
        var component = <HelloWidget name={dataFromDb.name} />;
        break;
}
React.render(
  component,
  document.getElementById('try3')
);

JSFiddle with all this code here: http://jsfiddle.net/61xdfjk5/

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

You could use an object as a lookup for the component type and keep the details of rendering it in one place:

var components = {
  'HiWidget': HiWidget,
  'HelloWidget': HelloWidget
}

var Component = components[dataFromObj.type]
React.render(
  <Component name={dataFromObj.name}/>,
  document.getElementById('try3')
)

Method 2

JSX is a superset of JavaScript, so you can always use native JavaScript syntax inside of JSX. For example, if classes of your components are available in global space (window), you can do the following:

React.render(
  React.createElement(window[dataFromDb.type], {name: dataFromDb.name}),
  document.getElementById('try2')
);

JSFiddle here.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x