Home > Blockchain >  Can I do a switch statement inside a return statement in react
Can I do a switch statement inside a return statement in react

Time:06-07

const Component = () => {
   let x = 1
   
   switch(x) {
   case 1: 
      return (
         <Component1 /> 
         <Component2 /> 
      )
   case 2: 
      return (
         <Component1 /> 
         <Component3 /> 
      )
   }
}

In the above code, in case 1, Component1 and Component2 are rendered while in case 2, Component1 and Component3 are rendered.

Is there a way to minimize repeated code by using a switch statement inside a single return statment eg.

const Component = () => {
   let x = 1
   
return (
   <Component1 /> 

   switch(x) {
   case 1: 
       <Component2 /> 
   case 2: 
       <Component3 />   
   }
}

CodePudding user response:

Is there a particular reason you NEED to use switch statement inside? You could as easily just use if else - if the conditions are not many.

You essentially can just make the switch a separate component just to do the logic instead on inside return.

Or you can look at answers here: How to use switch statement inside a React component?

Most elegant in my opinion if you have less conditions (<3) if to go for is else - and shorter ternary operators

CodePudding user response:

Yes, sort-of.

In React, functions that return Components must always return a single object: so if you want to return multiple Component objects (incl JSX) then you need to either wrap them in another outer Component - or return a JS array of components.

So that means if you want to return "Component1-and-Component2 OR Component1-and-Component3" then you should return an array, as either [ <Component1/>, <Component2/> ] or [ <Component1/>, <Component3/> ]` respectively.

...while the switch block in JavaScript itself is a statement and not an expression, JavaScript already has an expression equivalent: the ternary operator ?:, it's just slightly messier to deal with.

...but that means you can return a JS array literal with Compone use the ?:`

So try this:

const Component = () => {
   let x = 1
   
    return [
        // Element 0:
        <Component1 />,
        // Element 1:
        ( x == 1 ) ? <Component2 /> :
        ( x == 2 ) ? <Component3 /> :
        throw new Error( "This should never happen." )
    ];
}
  • Related