Search code examples
reactjs

How to use switch statement inside a React component?


I have a React component, and inside the render method of the component I have something like this:

render() {
    return (
        <div>
            <div>
                // removed for brevity
            </div>

           { switch(...) {} }

            <div>
                // removed for brevity
            </div>
        </div>
    );
}

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 (
        <div>
          <div>
              // removed for brevity
          </div>
          {this.renderSwitch(param)}
          <div>
              // removed for brevity
          </div>
        </div>
      );
    }