DEV Community

Brian Love
Brian Love

Posted on • Originally published at

Conditional Class Names in React


You can easily apply class names conditionally in React by leveraging an array of values, then join() each value with a space deliminator:

  className={['ui', 'button', !fixed && 'inverted', !!fixed && 'primary']
    .filter(c => !!c)
    .join(' ')}
  Launch Course
Enter fullscreen mode Exit fullscreen mode

How does it work?

This is because JavaScript conditionals are short-circuited when using the && (and) operator.

If the first conditional in the series of and conditionals is falsey, the remaining values in the conditional do not need to be checked, and the result is false.
If the first conditional in the series of and conditionals is truthy, then in sequence each subsequent value must be checked to verify the complete truthiness of the statement, and the result is the final value.

This concept is sometimes referred to as a guard.


There is one thing to be aware of.
The final value (or class name string in our case) must be evaluated as a truthy.
What is meant by that, is when JavaScript coerces the value to a boolean, you should be aware of the instances in which values can be coerced to be false.

So, if the class name (or value) is coerced to false when it is:

  • An empty string
  • The number 0
  • undefined
  • null
  • NaN

And as a result, the value will not be included in the final list of class names.

Top comments (2)

strdr4605 profile image
Dragoș Străinu

It is also possible to do

['ui', 'button', !fixed && 'inverted', !!fixed && 'primary']
    .join(' ')
blove profile image
Brian Love

Nice - even better. Thanks!