Non-generated classname selector in css module
Asked Answered
C

2

11

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

Cliff answered 23/7, 2020 at 9:54 Comment(1)
It seems you can only access customCard class which we pass as props nothing else :)Staysail
J
20

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

Joanajoane answered 29/7, 2021 at 9:40 Comment(1)
Nice. Simple and clear. Pretty straight forward. Thank you so much.Axilla
E
1

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>
Encore answered 25/11, 2022 at 21:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.