Create an instance of a React class from a string Create an instance of a React class from a string reactjs reactjs

Create an instance of a React class from a string


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];


No need to manually map your classes to a dictionary, or "registry", as in Michelle's answer. A wildcard import statement is already a dictionary!

   import * as widgets from 'widgets';   var Type = widgets[this.props.template];   ...   <Type />

You can make it work with multiple modules by merging all the dictionaries into one:

import * as widgets from 'widgets';import * as widgets2 from 'widgets2';const registry = Object.assign({}, widgets, widgets2);const widget = registry[this.props.template];

I would totally do this to get dynamic dispatch of react components. In fact I think I am in a bunch of projects.


I had the same problem, and found out the solution by myself. I don't know if is the "best pratice" but it works and I'm using it currently in my solution.

You can simply make use of the "evil" eval function to dynamically create an instance of a react component. Something like:

function createComponent(componentName, props, children){  var component = React.createElement(eval(componentName), props, children);  return component;}

Then, just call it where you want:

var homeComponent = createComponent('Home', [props], [...children]);

If it fits your needs, maybe you can consider something like this.

Hope it helps.