Elaine Byene
Elaine Byene

Reputation: 4142

Applying conditional CSS class to ReactJS code

I feel like i'm doing it correctly as per the documentations but it's not happening. I know there are similar questions but somehow my code isn't working. It's not compiling the class properly.

This is my code which is clickable if the user roles are correct.

<h4 
  onClick={(e) => {
    e.stopPropagation();
    if (this.props.role === 'owner' || this.props.role === 'member' || this.state.task.OwnerId === user_Proj.User.ID) {
      this.setState({MakeConfirm: true})
    }
  }}
  className="title {this.props.role === 'owner' ? 'owner__yes':'owner__no'}"
>
  Button
</h4>

The output isn't compiling the CSS class. Here's the output which needs fixing.

<h4 class="complete {this.props.role === 'owner' ? 'owner__yes':'owner__no'}">Button</h4>

Upvotes: 1

Views: 45

Answers (3)

Youssef Egla
Youssef Egla

Reputation: 1601

If you want to apply only single className

<h4 className={this.props.role === 'owner' ? 'owner__yes' : '' }>Hello</h4>

If you want to apply one className or another other

<h4 className={this.props.role === 'owner' ? 'owner__yes' : 'owner_no' }>Hello</h4>

If you want to apply fixed className and conditional

<h4 className={`my-fixed-class ${this.props.role === 'owner' ? 'owner__yes' : 'owner_no' }`}>Hello</h4>

You can also apply multiple conditional classNames

<h4 className={`my-fixed-class ${this.props.role === 'owner' ? 'owner__yes' : this.props.role === 'employee' ? 'employee-yes' : 'customer' }`}>Hello</h4>

You can also do something like this which will format the string result to either owner__yes or owner__no

<h4 className={`owner__${this.props.role === 'owner' ? 'yes' : 'no' }`}>Hello</h4>

Upvotes: 1

Yousaf
Yousaf

Reputation: 29282

Problem is that ternary operator isn't being parsed as javascript code because its wrapped in double quotes.

Change

className="title {this.props.role === 'owner' ? 'owner__yes':'owner__no'}"

to

className={'title ' + (this.props.role === 'owner') ? 'owner__yes':'owner__no'}

Notice the parenthesis around this.props.role === 'owner'. They are important because if you skip the parenthesis, javascript will first concatenate this.props.role with 'title' and then check if concatenated string is equal to 'owner'. To avoid this problem, wrap this.props.role === 'owner' in parenthesis.

Upvotes: 1

wentjun
wentjun

Reputation: 42526

This can be achieved with JavaScript's template literals:

<h4 
  className={`title ${this.props.role === 'owner' ? 'owner__yes':'owner__no'}`}
>
  Button
</h4>

Upvotes: 2

Related Questions