Create an instance of a React class from a string

ewan picture ewan · May 11, 2015 · Viewed 23k times · Source

I have a string which contains a name of the Class (this is coming from a json file). This string tells my Template Class which layout / template to use for the data (also in json). The issue is my layout is not displaying.

Home.jsx:

//a template or layout.
var Home = React.createClass({
  render () {
    return (
    <div>Home layout</div>
    )
  }
});

Template.jsx:

var Template = React.createClass({
  render: function() {
    var Tag = this.props.template; //this is the name of the class eg. 'Home'
    return (
        <Tag />
    );
  }
});

I don't get any errors but I also don't see the layout / Home Class. I've checked the props.template and this logs the correct info. Also, I can see the home element in the DOM. However it looks like this:

<div id='template-holder>
    <home></home>
</div>

If I change following line to:

var Tag = Home;
//this works but it's not dynamic!

Any ideas, how I can fix this? I'm sure it's either simple fix or I'm doing something stupid. Help would be appreciated. Apologies if this has already been asked (I couldn't find it).

Thanks, Ewan

Answer

Michelle Tilley picture Michelle Tilley · May 11, 2015

This will not work:

var Home = React.createClass({ ... });

var Component = "Home";
React.render(<Component />, ...);

However, this will:

var Home = React.createClass({ ... });

var Component = Home;
React.render(<Component />, ...);

So you simply need to find a way to map between the string "Home" and the component class Home. A simple object will work as a basic registry, and you can build from there if you need more features.

var components = {
  "Home": Home,
  "Other": OtherComponent
};

var Component = components[this.props.template];