Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React JSX in className if-else syntax [duplicate]

I am currently working on a react app where I am adding and changing classes based on certain state changes. It worked successfully in testing with a ternary operator but now I realized I will have to add mutiple else-if statements so I am trying to convert it to a classic if else format but am getting syntax errors and I'm not sure how to do it.

Here is the ternary operator that worked fine:-

<div className={"wrapper " + (this.state.hot ? 'wrapper-gradient-hot' : 'wrapper-gradient-cold')}>

Here is my attempt to make it a classic if-else in JSX and failed:-

<div className={"wrapper " + (
                        if (this.state.hot) {
                            return 'wrapper-gradient-hot';
                        } else {
                            return 'wrapper-gradient-cold';
                        }
                    )}>

Pls help me out :)

like image 965
user9069254 Avatar asked Oct 14 '25 03:10

user9069254


2 Answers

You can only use expressions inside of a React Component attribute. You'll need to move your logic into a function.

function temperatureClassname(temp){
  const prefix = 'wrapper-gradient-'

  switch (temp) {
    case 'hot':      return prefix + 'hot'
    case 'cold':     return prefix + 'cold'
    case 'ice-cold': return prefix + 'too-cool'
  }
}

And your react component would look like this:

<div className={ temperatureClassname(this.state.hot) }>
like image 164
THEtheChad Avatar answered Oct 16 '25 15:10

THEtheChad


If and else statements, are just that... statements. Inline JSX expressions that you wrap with {…} only allow expressions; statements are not expressions.

Your ternary approach is fine, though since there's some commonality between the two strings you can actually use interpolation:

<div className={`wrapper-gradient-${this.state.hot ? 'hot' : 'cold'}`}>
like image 45
Andrew Li Avatar answered Oct 16 '25 17:10

Andrew Li