Multiple classnames with CSS Modules in React

January 28, 2019
I'm making an alternative to DevTools. Click here to check it out.

If you want to use multiple classnames with CSS Modules in React, you can use classnames.1 Install it like so:

# with npm
npm install classnames --save

# or with yarn
yarn add classnames

When importing it, I like to call it cx instead of classnames since it looks cleaner.

import cx from 'classnames'

Then, pass it into className inside your component:

// Joining multiple CSS Modules classes
// <div class="foo-f93d72 bar-g9493s"></div>
<div className={cx(styles.foo, styles.bar)} />

// Conditionally displaying multiple CSS Modules classes
// <div class="foo-f93d72"></div>
<div className={cx(styles.foo, {[styles.bar]: false})} />

Obviously, instead of just false, you could pass a prop into that instead.

Using CSS Modules with classnames also gives us the ability to write some really beautiful scoped CSS. Pay attention to styles[type] in this example:

// Button.jsx
import React from 'react'
import cx from 'classnames'
import styles from './Button.css'

const Button = ({ type, text }) =>
  <button className={ cx(styles.button, styles[type]) }>
    { text }
  </button>
/* Button.css */
.button { /* common button styles here */ }
.danger { background: red; }
.save   { background: green; }

Now we can pass in a type prop to call a CSS Modules class! For example…

<Button type="danger" text="Delete Account" />

…would generate a button with both the .button and .danger styles.

  1. At the time of writing, classnames has about 3.5 million downloads per week. ↩︎