Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to combine multiple classNames in React?

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.

like image 366
ft-be Avatar asked Aug 16 '19 11:08

ft-be


2 Answers

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")}
like image 157
Amel Avatar answered Nov 13 '22 10:11

Amel


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`}>
...
like image 2
Volodym Dobrov Avatar answered Nov 13 '22 11:11

Volodym Dobrov