How do I prevent the css in one component from affecting the css in another component in React?

Viewed 2209

I'm new to React, so I'm not exactly sure why this is happening. Using the React Router, I have three routes, /, /signup, and /login, and the importing of css in each component spills over into the css of the other components, ruining the styling. In this case, instead of the div element word being the color as described in each component's css, they all come out green which should only happen for the Signup component. What can I do to fix this?

App.js

import HomePage from './pages/HomePage/HomePage'
import LoginPage from './pages/LoginPage/LoginPage'
import SignupPage from './pages/SignupPage/SignupPage'
import  {BrowserRouter as Router, Switch, Route} from 'react-router-dom'

function App() {
    return (
      <Router>
        <Switch>
          <Route path="/" exact component={HomePage}/> 
          <Route path="/signup" component={SignupPage}/>
          <Route path="/login" component={HomePage}/>
        </Switch>
      </Router>
    )
}

export default App;

LoginPage.js

import { React } from 'react'
import "./LoginPage.css"

export default function LoginPage(){
    return(
      //In css file, word is red, but comes out green instead
      <div className="word">login</div>
    )
}

SignupPage.js

import { React } from 'react'
import "./SignupPage.css"

export default function SignupPage(){
    return(
      //In css file, word is green
      <div className="word">signup</div>
    )
}

HomePage.js

import React, { useState } from 'react'
import "./HomePage.css"

export default function HomePage() {

    return (
         //In css file, word is hotpink, but comes out green instead
         <div className="word">Home</div>
    )

Is there something I need to add to my App.js file?

2 Answers

Create a top div for each page:

export default function HomePage() {
return (
     <div className="homepage"><div className="word">Home</div></div>
)

Do similarly for signup page.

Then in css

homepage.css

 .homepage .word{
     
      color:red;
    
  }

signup.css

.signup .word{
 
  color:green;

 }

Now depending if you use word class inside signup page or homepage (any level deep), word will have different styling.

The best way to prevent that is by using CSS Modules because CSS Modules let you use the same CSS class name in different files without worrying about naming clashes

Using CSS module is simple, just follow it's naming convention which looks like this, [name].module.css

Example: CSS className selectors of the following CSS modules, are independently

App.module.css

.container{
  color: #fff;
}

Navigation.module.css

.container{
  color: #000;
}

Click here to read more about CSS modules

Related