al8anp al8anp - 1 year ago 107
Javascript Question

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

var HiWidget = React.createClass({
render: function() { return <div>Hi {}</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 :

<dataFromDb.type name={} />,

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={} />;
case 'HelloWidget':
var component = <HelloWidget name={} />;

JSFiddle with all this code here:

Answer Source

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]
  <Component name={}/>,
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download