Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid CSS conflicts in ReactJs

I am not at all an expert in react, but from what I could see if I import some css sheets these will be for all my application. If I wanted to use react for a multi-page app how do I define css sheets for each page?

My file structure

Page 1

import React, { Component } from "react";
import "./style.css";

export default class Page1 extends Component {
  render() {
    return (
      <div>
        <button>with css</button>
      </div>
    );
  }
}

Page 2

import React, { Component } from "react";

export default class Page2 extends Component {
  render() {
    return (
      <div>
        <button>no css</button>
      </div>
    );
  }
}

style.css

button {
  background: green;
}

This style should only be applied to the first page but it is also applied to page 2. How can I solve this?

like image 325
Niccolò Caselli Avatar asked Mar 20 '19 17:03

Niccolò Caselli


2 Answers

The easiest way to avoid css conflicts beetwen pages on Reactjs is to use css-modules (it's not a dependency), just change your page stylesheet name from 'my-stylesheet.css' to 'my-stylesheet.module.css' and import it as 'my-stylesheet.module.css'.

like image 95
gianlop3z Avatar answered Oct 14 '22 00:10

gianlop3z


Here's a random react app:

enter image description here

What i do is i create CSS files for my containers (pages) and i import then within:

import './styleForComponent.css'

Style applies to child component and doesnt intefere with my other pages, if you want some global style you can import then in index.html as you would without React or import your css in your index.js

like image 43
Halt Avatar answered Oct 14 '22 00:10

Halt