HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptreactCritical

React / JSX Dynamic Component Name

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
jsxdynamicreactnamecomponent

Problem

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

For example:

var type = "Example";
var ComponentName = type + "Component";
return ; 
// Returns   instead of 


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

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.

EDIT:
As pointed out by gmfvpereira these days there is an official documentation entry for this:
https://reactjs.org/docs/jsx-in-depth.html#choosing-the-type-at-runtime

Solution

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


compiles to

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

Code Snippets

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

Context

Stack Overflow Q#29875869, score: 291

Revisions (0)

No revisions yet.