Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Pass in Props When Using CSS Modules

I have a button component and using Tailwindcss framework and css modules for additional styling which looks like the following. This works as I'm using template literal to pull in the red background styling.

CSS Module:

.red {
  background-color: red;
}

.blue {
  background-color: blue;
}

React Component:

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

const Button = props => {
  return (
    <button
      className={`text-white py-2 px-4 rounded ${styles.red}`}
    >
      Button
    </button>
  )
}

But what if I wanted the background to be flexible and receive props in order to determine background color? I was thinking something like the below but obviously doesn't work:

<button
  className={`text-white py-2 px-4 rounded ${styles.`${props.bgColor}`}`}
>
like image 596
Eric Nguyen Avatar asked Feb 06 '26 20:02

Eric Nguyen


1 Answers

Turns out, this is the correct syntax:

<button
   className={`text-white py-2 px-4 rounded ${styles[props.bgColor]}`}
>
like image 151
Eric Nguyen Avatar answered Feb 09 '26 11:02

Eric Nguyen