React style/css/sass order
Asked Answered
A

2

6

I have my "App-component" and a "B-component" that gets rendered inside my app component. Each has its own style.

But when it gets compiled, my ComponentB.css is put before my app.css, making the ComponentB styles being overwritten by my app styles.

Why is this happening??

APP

 import React, { Component } from 'react';
 import ComponentB from './components/ComponentB';
import './styles/app.css';

    class App extends Component {
      render() {
        return (
          <div className="App">
            <ComponentB />
          </div>
        );
      }
    }

    export default App;

COMPONENT B

import React, { Component } from 'react';
import './styles/ComponentB.css';

class ComponentB extends Component {
  render() {
    return (
      <div>
        <h1>Hello from ComponentB</h1>
      </div>
    );
  }
}

export default ComponentB;
Acedia answered 11/11, 2018 at 10:24 Comment(1)
For example my normalize css its import in my app.css but in the compilation my componentB.css it put before my app.css.Acedia
R
1

The css files are added to the html in the order they're imported. So to influence the order they're listed, go to your App.jsx and move the app.css import line above the ComponentB import line so it looks like:

import React, { Component } from 'react';
import './styles/app.css';
import ComponentB from './components/ComponentB';

Then, you'll get the behavior you're seeking.

Risley answered 28/6, 2023 at 17:17 Comment(0)
P
0

The way you do it results in a styles conflicts(one style overwriting another style), because after React compiles your code you are still using the same selectors for the same classes. If you want to use different css files for different components while using the same class names, you should use CSS modules.

This will make your CSS class names scoped locally by default.

Plethora answered 11/11, 2018 at 10:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.