Skip to content

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.

Answer

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.