How to combine multiple classNames in React?
Asked Answered
S

2

10

I'm writing a small React app with Create-React-App. For simple styling tweaks I use tachyons-css. Due to frequent reappearing CSS styling issues I recently switched from classic CSS styling to CSS modules (also valid question for SCSS). Now I wonder if there is a way to still use both - CSS modules and tachyons styling - even though it is not possible anymore to just add an additional "classic" className to the CSS module styles object.

Before using CSS modules I used to define a class and tachyons styling (padding5 in this example) by having multiple classNames. For example:

<ExampleComponent className="examplecomponentstyle pa5"/>

When using CSS modules the CSS class definition will now look like this:

<ExampleComponent className={styles.examplecomponentstyle}/>

How can this syntax now be combined with the previous usage of the tachyons styling? Is there something like this that could work?:

<ExampleComponent className={styles.examplecomponentstyle & "pa5"}/>

Thanks a lot!

UPDATE from 05-Sep-19:

The clsx package is exactly doing what I was trying to achieve. After installing clsx

npm install --save clsx 

the ExampleComponent can then e.g. be styled using clsx like this:

<ExampleComponent className={clsx(styles.examplecomponentstyle, "pa5 bg-yellow")}/>

UPDATE from 17-May-20:

As Sandip pointed out the ClassNames package can as well as the clsx package be used to achieve the same behaviour. The number of weekly downloads of both packages even indicates that ClassNames is much more frequently used than CLSX (~5.2 mio vs ~1.6 mio weekly downloads as of May 17 2020). This link on github discusses the performance differences between the two packages.

Sato answered 16/8, 2019 at 11:31 Comment(2)
You can even user npmjs.com/package/classnames.Lordling
Hi Sandip, thanks for your answer, classnames is defenitelly also a good solution and probably used much more frequently. This link is quite interesting regarding the slight difference in performance between the two packagesSato
P
6

Without any package:

className={[styles.examplecomponentstyle, "pa5"].join(" ")};

Like you already mentioned, the package clsx is pretty good:

className={clsx(styles.examplecomponentstyle, "pa5 bg-yellow")}
Perineurium answered 28/8, 2020 at 11:48 Comment(0)
W
2

When using CSS modules, you can combine classes like this

import styles from "./styles.module.css";
import "./index.css";
...
<div className={`${style.header} ${style.headerLight} container`}>
...
Waistcoat answered 29/8, 2022 at 12:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.