Ash Ash - 16 days ago 7
React JSX Question

Access global classes from within CSS module

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.

Answer

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;
}
Comments