Search code examples
reactjsswitch-statementconditional-rendering

How to use switch cases inside JSX: ReactJS


I have four components imported in my react app. How can i render one of the component conditionally (based on props). This is what i'm trying to do

<ReactSVGPanZoom
      //switch(this.props.Selected){
      // case '1': render <ComponentOne/>; break;
      // case '2': render <ComponentTwo/>; break;
      // case '3': render <ComponentThree/>; break;
      // case '4': render <ComponentFour/>; break;
      // default: render <ComponentOne/>
        }
</ReactSVGPanZoom>

Solution

  • Directly it's not allowed, because we can't put any statement inside JSX. You can do one thing, put the code (switch logic) inside a function and call that function, and return the correct component from that.

    Check doc for: Embedding Expressions in JSX

    Like this:

    <ReactSVGPanZoom
        {this.renderComponent()}
    </ReactSVGPanZoom>
    
    
    renderComponent(){
        switch(this.props.Selected){
            case '1': return <ComponentOne/>;
            case '2': return <ComponentTwo/>;
            case '3': return <ComponentThree/>;
            case '4': return <ComponentFour/>;
            default: return <ComponentOne/>
        }
    }
    

    Suggestion:

    break is not required after return.