ousmane784
ousmane784

Reputation: 446

React conditional classnames

I need to have a className of an item based on a list of conditions. What is the best way of doing this? Right now I have an array and I push the className to the array.

const classNames = [];

    if (alarm?.code === 'urgent') {
      classNames.push(styles.yellow);
    } else if (alarm?.code === 'error') {
      classNames.push(styles.red);
    } else if (alarm?.code === 'disabled') {
      classNames.push(styles.grey);
    } else if (alarm?.severity === 'info') {
      classNames.push(styles.blue);
    }

Then I add it to the element like this:

<div className={[...classNames]}></div>

My question is mainly, what is the difference between setting the classNames like this compared to using useState and useEffect?

Upvotes: 0

Views: 1435

Answers (2)

Mark Swardstrom
Mark Swardstrom

Reputation: 18080

There is a classnames npm module that does this. Or make a simple utility.

export const classnames = (...args) => args.filter(Boolean).join(' ')

Either would be used like

<div className={classnames(classNames)}>...</div>

Edit - Actually for this one, just separate out the classnames

const classNames = {
  urgent: styles.yellow,
  error: styles.red
  disabled: styles.grey
  info: styles.blue
}

<div className={classNames[alarm?.code]}></div>

In response to your question:

My question is mainly, what is the difference between setting the classNames like this compared to using useState and useEffect?

useState and useEffect are hooks designed to hold state between renders. If you need to trigger a re-render or take action on a change, then that's when you'd use those hooks. I don't see a need for those with classnames in this case.

Upvotes: 0

Vishal Rajole
Vishal Rajole

Reputation: 1544

You can check classnames package (it is also recommended by React official documentation here)

install with npm

npm install classnames --save

and use as

   const code = alarm?.code;
   const severity = alarm?.severity;

   <div
     className={classNames({
        yellow: code === 'urgent',
        red: code === 'error',
        grey: code === 'disabled',
        blue: severity === 'info'
     })} 
   </div>

Upvotes: 2

Related Questions