2

I'm using css modules and at the moment my method for assigning multiple classes to components is:

import {class1,class2 } from './styles.css' <div><Link to = 'auth' className= {[`${class1} ${class2}`]} >Login</Link></div>

this just doesnt seem efficient nor elegant.

2 Answers 2

1

You can use classnames (as mentioned by official react documentation)

link to github : https://github.com/JedWatson/classnames

const class = {class1:true,class2:onlyIfFalgisTrue};

then you can use it as

<div><Link to = 'auth' className= {class} >Login</Link></div>
Sign up to request clarification or add additional context in comments.

Comments

0

Yes there is a utility called classnames https://github.com/JedWatson/classnames

classNames('foo', 'bar'); // => 'foo bar'
classNames('foo', { bar: true }); // => 'foo bar'
classNames('foo', { bar: true, duck: false }, 'baz', { quux: true }); // => 'foo bar baz quux'

For your specific usage

const klassNames = classNames(`${class1} ${class2}`);
div><Link to = 'auth' className= {klassNames} >Login</Link></div> 

I agree you might say this is the same as your previous code but see if want to add classes based on some conditions this is highly beneficial

Another Example

const klassNames = classNames(`${class1}`, {
`${class2}`: someCondition === true,
`${class3}: someCondition === false
}

I am using in my large react project really solves if else conditioning for classes

Example

1 Comment

can you post an example, i tried to follow docs but still unclear

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.