1
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 />   
   }
}

Dai
  • 141,631
  • 28
  • 261
  • 374
ryantan
  • 79
  • 2
  • 7
  • To my knowledge, Functions returning Components must 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. – Dai Jun 07 '22 at 03:38

2 Answers2

2

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/> ]

...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 Component2 or Component3 as the last element, chosen with the ?: operator, like so:

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

Though if you know that x will always only ever be 1 or 2 then (in addition to using a custom type for x instead of number) then you can do just this:

const Component = () => {
    let x = 1
   
    return [
        <Component1 />,
        ( x === 1 ) ? <Component2 /> : <Component3 />
    ];
}
Dai
  • 141,631
  • 28
  • 261
  • 374
0

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

user18821127
  • 318
  • 1
  • 8