Search code examples
cssreactjsnext.jscss-modulesreact-css-modules

using a variable value on css modules class name


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?


Solution

  • 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>