4

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

1
  • Welcome on StackOverflow! :) Commented Mar 19, 2018 at 2:26

4 Answers 4

5

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) }>
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, your suggestion was just what I needed haha. I almost never use a switch statement but here it’s just perfect. Thanks :)
Glad I could help. Cheers =)
4

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'}`}>

Comments

1

One approach you could adopt is to handle this outside of your JSX. So, in your render function still but just above where you return.

render() {
  let gradientValue;
  // Put your if-else here and update gradientValue on each condition.
  return (
    <h1 className=`wrapper ${gradientValue}`>Your html here</h1>
  );
}

1 Comment

``` className={btn btn-secondary ${currency === 'INR' && 'active'}}```
0

return only returns values from inside a function, just putting parentheses around an if/else statement like that isn't going to work. You'd be better off sticking with the ternary operator, and nesting them as required.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.