Apply multiple css classes dynamically in React Js

Last updated : Jul 30, 2023 12:00 AM

I can use template literals to apply multiple CSS classes from a CSS module to an element. Here is how to implement it.

My Styles.module.css file contains the styles that I want to apply.

.buttonClass {
   background-color: green;
}
.buttonColor {
   color: white
}

I must import the Styles.module.css in the component where I want to use the styles. Then I use template literals to wrap the CSS styles I intend to use, leaving a space between class names.

import styles from "./Styles.module.css"

export const App = () => {
   return(
      <button className={`${styles.buttonClass} ${styles.buttonColor}`}>CSS Styles</button>
   )
}
export default App

Conditionally apply multiple CSS classes.

If I want to pick the CSS class names based on some conditions, here is how to do that.

.buttonClassGreen {
   background-color: green;
}
.buttonClassBlue {
   background-color: blue;
}
.buttonColor {
   color: white
}

I can accommodate the display logic within the template literals.

import { useState } from "react"
import styles from "./Styles.module.css"

export const App = () => {
const [random,] = useState<boolean>(Math.random() < 0.5)
   return(
      <button 
         className={`${random ? styles.buttonClassGreen : styles.buttonClassBlue} ${styles.buttonColor}`}
      >
         CSS Styles
      </button>
   )
}
export default App
Lance

By: Lance

Hi, I'm Lance Raney, a dedicated Fullstack Developer based in Oklahoma with over 15 years of exp

Read more...