Reputation: 5789
Given:
let component = [];
switch(foo) {
case 'bar':
component = <TheBarComponent/>
break;
case 'baz':
component = <TheBazComponent/>
break;
case ...
}
// set component properties here.
Given that all components in the switch
have the same props signature, how do I set them in one place rather than in-lining them all in each case
statement?
Upvotes: 1
Views: 1137
Reputation: 6435
When you use that <ComponentNameHere>
syntax with a name starting with a capital letter, it's shorthand for React.createElement(ComponentNameHere);
, which creates a component instance. Instances should be treated as immutable, so you don't want to be modifying it afterwards.
See the JSX In Depth page for full details.
Instead, remember that the "tag name" in JSX is just a regular javascript identifier, so you can set it dynamically, like this:
let Component;
switch(foo) {
case 'bar':
Component = TheBarComponent
break;
case 'baz':
Component = TheBazComponent
break;
case ...
}
let myComponent = <Component prop="value" />
Upvotes: 3