1

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 ?

2 Answers 2

1

You should use bracket

<div className={styles.colorBoxContainer}>
    {colors.map((color, index) => (
        <div
            className={`${styles[color]} ${styles.colorBox}`}
            key={index}
        ></div>
    ))}
</div>
Sign up to request clarification or add additional context in comments.

Comments

1

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>

1 Comment

Thanks, this approach didn't come to my mind :D But do you know how to apply those classNames, if we want to do something more than just backgroundColor ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.