Brian Love
Posted on December 12, 2019
tl;dr
You can easily apply class names conditionally in React by leveraging an array
of values, then join()
each value with a space deliminator:
<Link
to="/course"
className={['ui', 'button', !fixed && 'inverted', !!fixed && 'primary']
.filter(c => !!c)
.join(' ')}
>
Launch Course
</MenuButton>
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.
Gotchas
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.
Posted on December 12, 2019
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.