Abhishek Jha
Abhishek Jha

Reputation: 129

Multiple variable className in next js

How to apply multiple className in Next js, in which there are variable classsnames as well ?
I'm using component level css approach

Here's my code and what I want to do:

import styles from "./ColorGroup.module.css";

const colors = ["red", "sky", "yellow", "green", "golden"];

const ColorGroup = () => {
  return (
    <div className={styles.colorContainer}>
      <text>Colour</text>
      <div className={styles.colorBoxContainer}>
        {colors.map((color, index) => (
          <div
            // variable color class is not get applied, only colorBox is applied, I want both
            className={`${styles}.${color} ${styles.colorBox}`}
            key={index}
          ></div>
        ))}
      </div>
    </div>
  );
};

Goal:

enter image description here

CSS code:


/* code for layout and arrangement above */

.colorBox {
  height: 36px;
  width: 36px;
}

.red {
  background-color: lightcoral;
}
.sky {
  background-color: skyblue;
}
.yellow {
  background-color: lightyellow;
}
.green {
  background-color: lightgreen;
}
.golden {
  background-color: greenyellow;
}

But this method is only applying the colorBox className and not doing anything for ${styles}.${color} . How to apply both ?

Upvotes: 1

Views: 1898

Answers (2)

iamhuynq
iamhuynq

Reputation: 5529

You should use bracket

<div className={styles.colorBoxContainer}>
    {colors.map((color, index) => (
        <div
            className={`${styles[color]} ${styles.colorBox}`}
            key={index}
        ></div>
    ))}
</div>

Upvotes: 1

pnxdxt
pnxdxt

Reputation: 160

You can try to use the style object, it easier to use it with variables :

<div key={index} className={`${styles.colorBox}`} style={{ backgroundColor: color }} >
</div>

Upvotes: 1

Related Questions