Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 340
Vishnu Avatar asked Jan 27 '18 14:01

Vishnu


4 Answers

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.

like image 176
Mayank Shukla Avatar answered Oct 17 '22 01:10

Mayank Shukla


You can just get the component from the switch (either in a function or in-line in render) and render it as a child of ReactSvgPanZoom, like so:

getComponent(){
  switch(this.props.Selected){
    case '1': 
      return <ComponentOne/>;
    case '2': 
      return <ComponentTwo/>; 
    // .. etc
    default: 
      return <ComponentOne/>
  }
}
render() {
    return (<ReactSVGPanZoom>
        {this.getComponent()}
      </ReactSVGPanZoom>);
  }
like image 23
dashton Avatar answered Oct 17 '22 02:10

dashton


render() {
  return (
    <div>
      {
        (() => {
          switch(this.props.value) {
            case 1:
              return this.myComponentMethod();
              break;
            case 2: 
              return () => { return <AnotherComponent/> }; 
              break;
            case 3:
              return <div>1</div>; 
            break;
            default: return null; break;
          }
        }).call(this)
      }
    </div>
  )
}
like image 4
Sasha Kos Avatar answered Oct 17 '22 02:10

Sasha Kos


You can create a const and use it whenever you need:

import React from "react";

export const myComponents = {
  Component1: <Component1 />,
  Component2: <Component2 />,
  Component3: <Component3 />,
  Component4: <Component4 />,
}

now in your main component:

import React from "react";
import {myComponents} from "./const";

...
render() {
  return (
    <div>
      {myComponents[this.props.Selected]}
    </div>
  )
}

https://codesandbox.io/s/mzn5x725vx

like image 3
max li Avatar answered Oct 17 '22 02:10

max li