React / JSX Dynamic Component Name

Sam picture Sam · Apr 26, 2015 · Viewed 135.9k times · Source

I am trying to dynamically render components based on their type.

For example:

var type = "Example";
var ComponentName = type + "Component";
return <ComponentName />; 
// Returns <examplecomponent />  instead of <ExampleComponent />

I tried the solution proposed here React/JSX dynamic component names

That gave me an error when compiling (using browserify for gulp). It expected XML where I was using an array syntax.

I could solve this by creating a method for every component:

newExampleComponent() {
    return <ExampleComponent />;
}

newComponent(type) {
    return this["new" + type + "Component"]();
}

But that would mean a new method for every component I create. There must be a more elegant solution to this problem.

I am very open to suggestions.

Answer

Alexandre Kirszenberg picture Alexandre Kirszenberg · Apr 26, 2015

<MyComponent /> compiles to React.createElement(MyComponent, {}), which expects a string (HTML tag) or a function (ReactClass) as first parameter.

You could just store your component class in a variable with a name that starts with an uppercase letter. See HTML tags vs React Components.

var MyComponent = Components[type + "Component"];
return <MyComponent />;

compiles to

var MyComponent = Components[type + "Component"];
return React.createElement(MyComponent, {});