I want to apply multiple classes to a component using a ternary operator. There is a shared ts theme file that includes the general button styles, but I would like to display their sizes in this particular component differently depending on screen width, so have added locally scoped classes for this too.
What is the best approach for this?
...tried this, not working:
...got it working using classNames.
I usually use a small npm package called classNames
: https://www.npmjs.com/package/classnames.
It exposes a function that takes a variable number of arguments. If you give strings, they will be basically joined with a space, so you have them all applied:
<Button className={ classNames('first', 'second') } ...
Will be like doing:
<Button className="first second" ...
A nice feature that this package has, is that it can take an object where the key is the class and the value is a boolean that indicates whether to add this class or not, something like:
<Button className={ classNames({ even: index % 2 === 0, disabled: props.isDisabled }) } ...
Now, if index
is something like 2
, the even
class is added to the element.
You can use clsx, I think it's already installed if you use material-ui, and you can see that in material-ui's documentation examples.
import clsx from 'clsx';
// Bellow examples are from the clsx npm site:
// Strings (variadic)
clsx('foo', true && 'bar', 'baz');
//=> 'foo bar baz'
// Objects
clsx({ foo:true, bar:false, baz:isTrue() });
//=> 'foo baz'
// Objects (variadic)
clsx({ foo:true }, { bar:false }, null, { '--foobar':'hello' });
//=> 'foo --foobar'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With