React CSS - how to apply CSS to specific pages only
create-react-app, reactjs
Solution
Create react app will bundle all your css files into one so all the styles will be available everywhere in you app (on every rendered component). Be aware that CRA is a Single-Page Application (SPA) so you can't think in "pages" but rather in "rendered component" in the DOM.
You have multiple solutions:
1- Be organized in you css files : prefix all your classes by your component name to avoid conflict (like BEM) or use css hierachy `.my-component > .my-class {...}`
<div className="my-component">
<span className="my-class">Hello</span>
</div>
2- declare all your style in your JSX files:
const styles= {
myComponent: {
fontSize: 200,
},
};
const myComponent = () => (
<span style={styles.myComponent}>Hello</span>
);
the downside is that your styles will not be vendor prefixed by default.
3- Eject or use a fork of react-scripts (the engine of CRA) to use CSSModules (https://github.com/css-modules/css-modules)
Problem
I am using `create-react-app` and I am trying to work out an "efficient" way to apply stylesheets to specific pages. My `src` folder structure looks something like this: ``` | pages | - About | - - index.js | - - styles.css | - Home | - - index.js | - - styles.css | index.js | index.css ``` In each of the `index.js` files I use `import './style.css'` However, I'm finding that when I navigate from one page to the next the styles from the starting page are being applied to the target page as if they're being cached and the styles from the target page are not being followed. I just wondered if I'm misunderstanding how to apply styles in React to specific pages. Should I be making entirely self contained components which incude the styles too? I am considering applying them inline but I realise there are limitation when using JS styles.