Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReactJS styles 'leaking' to other components

So I have two components... a Navbar component, and an AboutPage component.

They are both in the same directory, 'App'

App

-- Navbar --> Navbar.css, Navbar.js

-- AboutPage --> Aboutpage.css, Aboutpage.js

So as you can see, they have two separate stylesheets. In the JS pages the correct CSS file is being imported as well.

When I do a style like this for example:

Navbar Component

p { background: red }

^^ this style also applies to the p's in the Aboutpage. I even tried to give the P in Aboutpage its on id and style it that way and it still failed.

like image 624
Eddie Taliaferro Avatar asked Mar 29 '18 02:03

Eddie Taliaferro


People also ask

Should each React component have its own CSS?

Separate CSS files One last thing, create a separate CSS file for each React component. Keeping separate CSS will make it much easier to find the CSS you're looking for. It's also easier to keep smaller CSS files organized and current.


2 Answers

That's the expected behaviour.

No matter which file you specify a rule like p { background: red }, it's going to be applied to all DOM. Specifying and id attribute to won't work either. The above rule is general enough to apply to all <p>s.

If you want to specify css files for each component, you should also create component specific css classes. Like the following example.

import React from 'react';
import './DottedBox.css';

const DottedBox = () => (
  <div className="DottedBox">
    <p className="DottedBox_content">Get started with CSS styling</p> 
  </div>
);

export default DottedBox;

and its css file:

.DottedBox {
  margin: 40px;
  border: 5px dotted pink;
}

.DottedBox_content {
  font-size: 15px;
  text-align: center;
}

If you want different ways of defining css for React, this resource adds 3 more ways of doing so, in addition to the above way.

like image 146
diogenesgg Avatar answered Oct 21 '22 09:10

diogenesgg


You can also use css modules. They scope your CSS locally and are awesome

like image 3
Kisho Avatar answered Oct 21 '22 10:10

Kisho