Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Switch case inside JSX not working: ReactJS

Tags:

reactjs

In my reactjs component - in the render, I want to create a switch case that will use particular components based on a switch case. But there is a syntax error here.

Should I just make this as a function inside the component?

Unexpected token (190:32)

  188 | 
  189 |   {
> 190 |     return (
      |     ^

Here is the full return function for the component:

return (
    <div className="Page">
        ....
    {
        elements.map(function(element, index){
            return (
                <Col xs={24} sm={element["grid-width"]*2} md={element["grid-width"]} key={index} className="element-container">
                  .....
                      <div className="contents">
                        {
                          return (
                            switch (element.type) { 
                              case 'we-are-always-here-to-help':
                                sss
                                break;
                              case 'call-us-when-you-are-having-difficulties':
                                xx
                                break;
                              default: 
                            }
                          )
                        }
                      </div>
                </Col>
            )
        })
    }
    </div>
)
like image 852
The Old County Avatar asked Mar 08 '23 05:03

The Old County


1 Answers

Rule:

We can put any expression not statement inside JSX by using {}.

It's not a valid syntax, we can not use switch statement or any other statement directly inside JSX.

Solution:

Put all the switch part logic inside a function, call that function from JSX and return the result.

Write it like this:

<div>
    {this._switchPart(element.type)}
</div>

Define _switchPart like this:

_switchPart(type){
    switch (type) {
       case 'we-are-always-here-to-help': return sss;

       case 'call-us-when-you-are-having-difficulties': return xx;

       default: return xy;
    } 
}

Or use ternary operator for conditional rendering or you can also use IIFE.

like image 184
Mayank Shukla Avatar answered Mar 27 '23 11:03

Mayank Shukla