snippetreactCritical
How to use switch statement inside a component?
Viewed 0 times
useswitchstatementinsidehowcomponent
Problem
I have a React component, and inside the
Now the point is that I have two
render method of the component I have something like this:render() {
return (
// removed for brevity
{ switch(...) {} }
// removed for brevity
);
}Now the point is that I have two
div elements, one at the top and one at the bottom, that are fixed. In the middle I want to have a switch statement, and according to a value in my state I want to render a different component. So basically, I want the two div elements to be fixed always, and just in the middle to render a different component each time. I'm using this to implement a multi-step payment procedure). Though, as is the code currently it doesn't work, as it gives me an error saying that switch is unexpected. Any ideas how to achieve what I want?Solution
Try this, which is way cleaner too: Get that switch out of the render in a function and just call it passing the params you want. For example:
renderSwitch(param) {
switch(param) {
case 'foo':
return 'bar';
default:
return 'foo';
}
}
render() {
return (
// removed for brevity
{this.renderSwitch(param)}
// removed for brevity
);
}Code Snippets
renderSwitch(param) {
switch(param) {
case 'foo':
return 'bar';
default:
return 'foo';
}
}
render() {
return (
<div>
<div>
// removed for brevity
</div>
{this.renderSwitch(param)}
<div>
// removed for brevity
</div>
</div>
);
}Context
Stack Overflow Q#46592833, score: 507
Revisions (0)
No revisions yet.