Reputation:
I am using create-react-app.
/Components
/C1
main.jsx
styles.scss
/C2
main.jsx
styles.scss
index.jsx
C1/main.jsx
.. .. .
import './styles.scss'
.. .. .
render(){
return(
<div className='test'>C1</div>
)
}
C1/styles.scss
.test{
color: red;
}
C2/main.jsx
.. .. .
import './styles.scss'
.. .. .
render(){
return(
<div className='test'>C2</div>
)
}
C2/styles.scss
.test{
color: green;
}
index.jsx
.. .. .
import C1 from './C1/main'
import C2 from './C2/main'
.. .. .
render(){
return(
<>
<C1 />
<C2 />
</>
)
}
Output
C1 <= This should be red
C2
As ReactJS bundles all .scss
to one .css
file maybe that's the problem.
How can I make these class names unique by making some change in webpack or code? As you know it's kinda hard to maintain unique class names because we cann't avoid names like header
, nav
, footes
etc to clash.
Upvotes: 1
Views: 6462
Reputation: 1
I assume you are importing scss files in the root of react application. Instead, you can import files only on the component that you want the classes to apply.
example: c2 main.js must import scss only under c2
This might solve your problem
Upvotes: 0
Reputation: 802
One way of doing that is by using CSS Modules
CSS Modules allows the scoping of CSS by automatically creating a unique classname of the format [filename]_[classname]__[hash].
CSS Modules let you use the same CSS class name in different files without worrying about naming clashes.
/*Button.module.css file*/
.error {
background-color: red;
}
/*another-stylesheet.css file*/
.error {
color: red;
}
import React, { Component } from 'react';
import styles from './Button.module.css'; // Import css modules stylesheet as styles
import './another-stylesheet.css'; // Import regular stylesheet
class Button extends Component {
render() {
// reference as a js object
return <button className={styles.error}>Error Button</button>;
}
}
Then the button in the example resolves to something like this
<!-- This button has red background but not red text -->
<button class="Button_error_ax7yz">Error Button</button>
Upvotes: 4