Search code examples
csscss-modulesreact-css-modules

Non-generated classname selector in css module


Let's say we have a third-party CardComponent like this

<Card title="This is a title in the header">This is text in the body</Card>

And this renders in plain HTML

<div class="Card">
  <div class="CardHeader"></div>
  <div class="CardBody"></div>
</div>

And I'm using css modules for styling (scss in this case).

.customCard {
  .CardBody {
    color: red;
  }
}

And then add the class to Card

import styles from ...
...
<Card className={styles.customCard} ...>...</Card>

Above will not work because it creates a generated class for CardBody like CardBody_sjkdh43. Is there a way to select non generated classnames in modules? Or is this only possible in the old fashion way to use a stylesheet?

Demo SandBox


Solution

  • The answer is to use the :global() selector in CSS modules.

    For more info: Exceptions - CSS Modules

    Example the code:

    <div class={styles.myClass}>
        <SomeComponentWithOwnCss />
    </div>
    

    Output:

    <div class="myClass_s4jkdh3">
        <div class="SomeComponentWithOwnCss"></div>
    </div>  
    

    And CSS:

    .myClass div:global(.SomeComponentWithOwnCss) {
        background-color: red;
    }
    

    Working example here: codesandbox