Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React.js question: How do I apply multiple classes to a component using a ternary operator?

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.

enter image description here

What is the best approach for this?

...tried this, not working:

enter image description here

...got it working using classNames.

like image 827
AKL012 Avatar asked Mar 04 '23 10:03

AKL012


2 Answers

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.

like image 174
0xc14m1z Avatar answered Apr 30 '23 02:04

0xc14m1z


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'
like image 45
amirhaa Avatar answered Apr 30 '23 03:04

amirhaa