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

1
  • It seems you can only access customCard class which we pass as props nothing else :) Commented Jul 23, 2020 at 11:25

2 Answers 2

21

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

Sign up to request clarification or add additional context in comments.

1 Comment

Nice. Simple and clear. Pretty straight forward. Thank you so much.
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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.