Stutje
Stutje

Reputation: 844

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

Upvotes: 11

Views: 3502

Answers (2)

Ryan Norooz
Ryan Norooz

Reputation: 1673

You could try this for a more convenient approach with SCSS:

.parent :global {
  .non-cssmodule-class {
    color: red;
  }
}
<div className={styles.parent}>
  <div className="non-cssmodule-class" />
</div>

output:

<style>
  .filename-parent__7MR41 .non-cssmodule-class { color: red; }
</style>
<div class="filename-parent__7MR41">
    <div class="non-cssmodule-class"></div>
</div>

Upvotes: 1

Closery
Closery

Reputation: 968

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

Upvotes: 20

Related Questions