Search code examples
cssreactjscss-modules

How to target CSS module classes after they are hashed?


I'm working in react and have an element that uses CSS modules for styling, like so:

<div className={styles.book__title}>Title: {book.title}</div>

Because class names are hashed, the compiled output is something like:

<div class="book__title_adsfj4">Title: The Lord of the Rings</div>

I've added an event listener on a button that, when pressed, adds the 'title' class to this element to offer additional styling for that specific class, like so:

<div class="book__title_adsfj4 title">Title: The Lord of the Rings</div>

Is there a way where I can either:

  1. append a class to an element and within my css file not have that class be hashed or
  2. add a class to an element that exactly matches the final compiled hash name?

Thanks.


Solution

  • I wrote about the best way I've found to do this here - https://github.com/css-modules/css-modules/issues/199

    Basically, it's just importing those styles from the original css file. Because those styles are all hashed the same, no matter if they are imported within different files, the styling will carry over.