Search code examples
javascriptreactjscheckboxinlineternary

React inline style with ternary


Having a Checkbox element like this:

<Checkbox
    checked={this.props.someValues.indexOf(myValue) > -1}
/>

When that index has a positive value the checkbox gets checked.

I want to add different colors to the checkbox, for example if it is unchecked - blue, checked - red.

So I tried to do it like this:

<Checkbox
   checked={this.props.someValues.indexOf(myValue) > -1}
   {(this.props.someValues.indexOf(myValue) > -1) ? style={{ color: 'red' }} : style={{ color: 'blue' }}}
   />

but it doesn't work.

Another try:

<Checkbox
   checked={this.props.someValues.indexOf(myValue) > -1}
   style={(this.props.someValues.indexOf(myValue) > -1) ? {{ color: 'red' }} : {{ color: 'blue' }} }
   />

Is it possible to set the style inline with ternary operators and I'm doing it wrong or should I try a different way?


Solution

  • Your second try only doesn't work because you have too many {} in it. Remember that the outer {} around the property value are to delimit a JSX expression; the contents of the expression are just JavaScript, so an object just uses a single pair of {}.

    But I wouldn't create separate objects (though that's fine), I'd just switch out the value:

          v−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−v−− JSX expression delimiters
    style={{color: this.props.someValues.indexOf(myValue) > -1 ? 'red' : 'blue' }}
           ^−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−^−−− Object literal delimiters
    

    But just for completeness, your second attempt corrected looks like this:

          v−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−v−− JSX expression delimiters
    style={this.props.someValues.indexOf(myValue) > -1 ? { color: 'red' } : { color: 'blue' } }
                                                         ^−−−−−−−−−−−−−−^−−−^−−−−−−−−−−−−−−−^−−−− Object literal delimiters
    

    ...and that way is fine too.