0

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?

2
  • Not sure if its the best way but alternatively you can do it this way alarm?.code === 'urgent' && styles.openButton and so on Commented Feb 17, 2021 at 19:06
  • I think that method would make it much harder to read and alot more extra code Commented Feb 17, 2021 at 19:25

2 Answers 2

2

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> 
Sign up to request clarification or add additional context in comments.

1 Comment

I cant be using extra packages I shouldve included it in the question
0

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.

1 Comment

I cant be using extra packages I shouldve included it in the question

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.