0

Currently I am using the ternary operator as shown below. I want to use switch-case for the same logic instead of using ternary operator. How to use it, is it possible to use switch case in return.

return(
    <>
      {
        props.page === 1?
        <h1> Hello </h1>
        :" "

      :
        props.page === 2?
        <h1> Hi </h1>
        :" "
   
      :
        props.page === 3?
        <h1> Good morning </h1>
        :" "

   </>  
 );
};
UserD
  • 41
  • 7
  • Check if this answers your question https://stackoverflow.com/questions/48477037/how-to-use-switch-cases-inside-jsx-reactjs – Vishnu Feb 23 '22 at 04:53

2 Answers2

2

You can create a function like message() that takes the props.page as an argument and returns the desired heading.

Like this

function message(page){
  switch(page){
   case 1:
    return "good morning"
   case 2:
    return "good night"
   }
}

function Home(props){
    return (
      <h1>{message(props.page)}</h1>
    )
}

Or you can also return JSX through the Message function.

Samathingamajig
  • 11,839
  • 3
  • 12
  • 34
Aashish Peepra
  • 176
  • 2
  • 8
0

Define switch case in a function and call that function by passing parameters

switchPage(page) {
    switch(page) {
        case 1:
            return 'Hello';
        case 2:
            return 'Hi';
        default:
            return 'Good morning';
    }
}

return (
    <>
        <h1>{this.switchPage(props.page)}</h1>
    </>
);
Sahil Thummar
  • 1,926
  • 16
  • 16