user8273956
user8273956

Reputation:

How can I make class names unique for my ReactJS components?

I am using create-react-app.

This is the directory structure of my components.

/Components
  /C1
    main.jsx
    styles.scss
  /C2
    main.jsx
    styles.scss
  index.jsx

Files

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

Answers (2)

Pavan K
Pavan K

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

Abido
Abido

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.

Example from Create React App guides page:

/*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

Related Questions