Home > other >  How to use switch-case in react render or return
How to use switch-case in react render or return

Time:02-23

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>
        :" "

   </>  
 );
};

CodePudding user response:

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.

CodePudding user response:

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>
    </>
);
  • Related