Search code examples
cssreactjswebpackwebpack-style-loader

Overlapping CSS in React, Webpack application


I have created an application using webpack and reactjs. So far I have created 2 pages. I have defined CSS styling for both the pages. But when I load page 2 after loading page 1, the styles from page 1 are interfering with those of page 2.

For example

Page 1

require('style1.css');
var Page1 = React.createClass({
render: function(){
  return(
<div> <h1>This is Page1</h1> <span> hello from page1</span></div>
 )
}
});

module.exports = Page1;

style1.css

span {
   color : red
}

Page 2

require('style2.css');

var Page2 = React.createClass({
render: function(){
  return(
<div> <h1>This is Page2</h1> <span> hello from page2</span></div>
 )
}
});

module.exports = Page2;

style2.css

h1 {
   color : blue
}

When page2 is loaded after page1, the color of span was red, which was loaded from page1's style. Is there any way to avoid such kind of interferences or am I doing something wrong here?


Solution

  • You can have local stylesheets for each React component.

    So the style sheet itself will have something like this:

    :local(.styles) {
    
      .your-style{...}
    }
    

    You can store it in the same folder as your component code. You import the style like so:

    /* component styles */
    import { styles } from './styles.scss'
    

    In the render function of your component you will have this:

    return (
      <div className={styles}>
      ...
      </div>
    )
    

    Everything within that <div> will have the stylesheet applied.

    Loader configuration for your Webpack:

    loaders: [{
      test: /\.scss$/,
      loader: 'style!css?localIdentName=[path][name]--[local]!postcss-loader!sass',
    }]
    

    You can look at this awesome boilerplate app, that implements all of this very nicely.