3

I'm trying use use a variable in a class name with css modules in nextjs, but I'm having a bad time figuring out the right syntax.

my variable comes from the api:

const type = red

how i'm trying to do it:

<div className={` ${styles.background} ${styles.--type}`}></div>

The result that I expect:

<div className={` ${styles.background} ${styles.--red}`></div>

is there a way to do it?

2
  • You mean styles[type]? You seem to be mixing up CSS variables with regular JavaScript variables. Commented Apr 10, 2021 at 23:59
  • i'm not using any css variables actually, I just want to use a variable value as a class name with css modules Commented Apr 11, 2021 at 0:47

1 Answer 1

7

Not sure what you are trying to achieve.

One solution could be to do :

const type = 'red';

<div className={`${styles.background} ${styles.type}`}></div>

However if you want to use BEM and the -- notation. You' might have to switch to brackets notation.

const type = '--red';

<div className={`${styles.background} ${styles[type]}`}></div>
Sign up to request clarification or add additional context in comments.

1 Comment

I believe the first solution still needs bracket notation around type

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.