Jason Krowl
Jason Krowl

Reputation: 114

css styles not applied CSS Modules react

I am using react-scripts: 5.0.1 with module.css files where I have my styles. One of my style files looks something like this. First I have to note that some module.css works fine. It seems the problem might be with the classNames.bind but I am not sure, I am kind of new to this problematic.

.rectangle {
  height: 100%;
  padding-top: 3px;
  & > .title {
    color: var(--red-70);
    font-size: 16px;
    line-height: 20px;
    margin-right: 12px;
  }
  & > .value {
    color: white;
    font-size: var(--message-text-size);
    line-height: var(--message-text-size);
    white-space: nowrap;
  }
}

I then import this file to my jsx file.

import style from './styles.module.css'

after that I use it as following

const cx = classNames.bind(style);

const Rectangle = ({ title, value }) => (
  <Stack className={style.rectangle}>
    <div className={style.title}> { title } </div>
    <div className={style.value}> { value } </div>
  </Stack>
);

The issue is that the styles are not applied at all. Result as on images.enter image description here enter image description here

Any way to fix this? I did not touch the webpack config at all from cra.

Upvotes: 0

Views: 965

Answers (1)

Gabriel CM
Gabriel CM

Reputation: 11

I created this code sandbox to reproduce this behavior and find out two things:

  1. The CSS code you provided had nested classes and searching about I find out this feature is not supported natively, only with pre-processors like Saas, etc. So the solution was to unested the classes, like this:
.rectangle {
  height: 100%;
  padding-top: 3px;
}

.title {
  color: var(--red-70);
  font-size: 16px;
  line-height: 20px;
  margin-right: 12px;
}

.value {
  color: white;
  font-size: var(--message-text-size);
  line-height: var(--message-text-size);
  white-space: nowrap;
}
  1. The classNames.bind() was not necessary to make things work, so I just commented it out. But searching about this approach, this classnames appear to be part of a library and the right way to use would be something like that, based on this link:
const cx = classnames.bind(style);

const Rectangle = ({ title, value }) => (
  <Stack className={cx('rectangle')}>
    <div className={cx('title')}> { title } </div>
    <div className={cx('value')}> { value } </div>
  </Stack>
);

Upvotes: 1

Related Questions