1

I'm working on a project that uses ReactJS and CSS modules with each react component having a corresponding SASS file.

When writing the CSS each class gets appended with the 'triple underscore random string' e.g. .myClass__e7G3A

My app appends a class (top' or 'down') to the body tag depending on scroll position and I want my component to respond to this.

The problem I have is if I add either .top or .down within the CSS module then it appends the unique identifier to the end of that class too.

e.g.

JSX:

<div className={styles.main}>
  Main content goes here.
</div>

Rendered HTML:

<body class="top">
  <div class="main___iZy2A">
    Main content goes here.
  </div>
</body>

SASS file:

.top .main {
  margin-top: 0;
}
.down .main {
  margin-top: 100px;
}

Compiled CSS:

.top___Gvf3S .main___iZy2A {
  margin-top: 0;
}
.down___kpd3S .main___iZy2A {
  margin-top: 100px;
}

Desired CSS outcome: (.top and .down without unique identifier)

.top .main___iZy2A {
  margin-top: 0;
}
.down .main___iZy2A {
  margin-top: 100px;
}

I'm sure I'm just missing a simple identifier or something that could achieve this.

Hope you can help. Thanks.

1 Answer 1

8

Use :global on the selector:

:global(.top) .main___iZy2A {
  margin-top: 0;
}
:global(.down) .main___iZy2A {
  margin-top: 100px;
}

Or a combination of :global and :local if you have more the one global selector:

:global .top .top--left :local .main___iZy2A {
  margin-top: 0;
}
:global .down .down--right :local .main___iZy2A {
  margin-top: 100px;
}
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks. I figured it would be something simple.
I get 'Error: composition is only allowed when selector is single :local class name not in' when attempting to do just this. Do you have any ideas where this might be coming from?
Seems like a problem in the configuration of your CSS modules. Check the css loader if you're using webpack.

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.