johnwick0831
johnwick0831

Reputation: 948

Css classname not applied to react component

I appreciate your time and help. I spent hours trying to figure this out can't seem to get to the bottom of it.

I have this react component:

import styles from './style.scss';

class ButtonComponent extends React.Component { 
  render() {
    return (
      <div className={styles.bunny}>
        hello world
      </div>
    );
  }
}

and scss file:

.bunny {
  display: block;
  margin-top:50px;
  margin-bottom:55px;
  background-color: blue;
}

When I load up my html, the div has no classname when I expect it to be <div class="bunny">

When I put the class name in the react component literally like this:

<div className="bunny"> 

then I can see the className in the browser.

What am I doing wrong?

Thank you so much in advance.

Upvotes: 8

Views: 9992

Answers (7)

二号去听经
二号去听经

Reputation: 1

module.exports = {
  entry: __dirname + '/index.js',
  output: {
    publicPath: '/',
    filename: './bundle.js'
  },
  module: {
    loaders: [
      {
        test: /\.jsx?$/,
        exclude: /node_modules/,
        loader: 'babel',
        query: {
          presets: ['es2015', 'stage-0', 'react']
        }
      },
      {
        test: /\.css$/,
        loader: "style-loader!css-loader?modules"
      },
    ]
  }
};

Check if the module query parameter exists in your css-loader configuration. If not, add it, This means that the cssModel is opened, And your className will eventually be compiled to a globally unique string

Upvotes: 0

D. Schmidt
D. Schmidt

Reputation: 167

I had different problem, that is not mentioned here, but that causes the same behavior (the class name is just not added to the output): Make sure you use a valid css identifier for your class name.

I used snake-case:

.spanning-grid-item {
  flex-grow: 1;
}

But I should have used camelCase instead:

.spanningGridItem {
  flex-grow: 1;
}

Upvotes: 0

UPS
UPS

Reputation: 11

there was a similar problem. It turned out that I named the style file not news.module.scss, but news.modules.scss. After renaming "modules" to "module" and then importing the file, className started working

Upvotes: 1

FrankGod
FrankGod

Reputation: 91

For me it's because I use commonjs's require to load an es module.

Upvotes: 0

Chris HG
Chris HG

Reputation: 1492

What fixed this for me was to change the name of my scss file from style.scss to style.module.scss

Upvotes: 0

Luke Flournoy
Luke Flournoy

Reputation: 3733

You need to import your scss like... import './styles.scss';

Webpack will take care of bundling your styles so you can add the className as a string on your component.

<div className="bunny">Hello World</div>

Upvotes: 1

Bing Nguyen
Bing Nguyen

Reputation: 69

Firstly, you need to guarantee it's defined with: console.log(styles) Im' not sure you import style.scss correctly.

Upvotes: 2

Related Questions