bobby
bobby

Reputation: 183

React JS How to make components unaffected by CSS?

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


class NavBar extends Component {




  render() {
    return (
      <div>

          navbar stuff



      </div>


    );
  }
}

export default NavBar;

If I were to import NavBar to another file and place it.

import React, { Component } from "react";
import NavBar from './NavBar'
import './randomfile.css'


class somefile extends Component {

  render() {
    return (
      <div id="test">

          <NavBar />


      </div>


    );
  }
}

export default somefile;

How do I prevent the CSS to affect my navbar? I'm trying to work with components but I've fallen into a bunch of CSS on my components when I just want the CSS i have in my NavBar file

randomfile.css

#test div {
    text-align: left;
}

^ Makes everything under div align to the left

Upvotes: 2

Views: 161

Answers (1)

duc mai
duc mai

Reputation: 1422

it depends on how the other css files are written like if they use very general rules such as elements matches so there is no way to prevent 100%. However you can minimize the impact by using.

  • Follow BEM for your styles, http://getbem.com/, so your styles will be tighter and it is usually specific for your components.
  • Use css in js libraries like styled-components, https://www.styled-components.com/, this way your css rules will be very strong and it is often enough to rule other rules outside.

I my self used to use BEM before, recently I have adopted css in js and been using styled components for most of my projects recently and it works quite well.

Upvotes: 2

Related Questions