Using CSS files that are not properly imported into React components

Currently, I am utilizing multiple CSS files for a specific purpose. The issue I am facing is that when I apply styles to one component in a CSS file, it inadvertently affects other components as well, not just the intended one.

I believe the root of this problem lies within react-router. It seems to be sharing CSS files across all components imported into it. When a component is no longer used in the router, its associated CSS files are no longer shared.

But how can I approach routes differently? I need to import all components into the router in order to have links to my pages.

I even attempted placing routes in separate files, but that did not resolve the issue either.

This is what my route file structure looks like:

import React, { Component } from 'react';
import {
  BrowserRouter as Router,
  Route
} from 'react-router-dom';

import './App.css';
import LoginPage from '../pages/LoginPage.js';
import Navbar from './Navbar.js';
import MainPage from '../pages/MainPage.js';
import SportsfieldsListPage from '../pages/SportsfieldsListPage.js';
import MyProfilePage from '../pages/MyProfilePage.js';
import SingleObjectPage from '../pages/SingleObjectPage.js';
import ConfirmPage from '../pages/ConfirmPage.js';
import AdminPage from '../pages/AdminPage.js';

class App extends Component {
  render() {
    return (
      <Router>
        <div className="container">
        <Navbar />
          <Route exact path="/" component={MainPage} />
          <Route exact path="/listaBoisk" component={SportsfieldsListPage} />
          <Route exact path="/LoginPage" component={LoginPage} />
          <Route exact path="/MyProfilePage" component={MyProfilePage} />
          <Route path="/object/:id" component={SingleObjectPage}/>
          <Route path ="/confirm/:id/:value" component={ConfirmPage}/>
          <Route path ="/adminPage" component={AdminPage}/>
        </div>
      </Router>
    );
  }
}

export default App;

Answer №1

If you're looking to keep your CSS styles organized in your project, consider using CSS modules. With CSS Modules, unique class names are automatically generated for each component.

Alternatively, if you prefer not to use CSS Modules, you can utilize CSS class nesting. For example, for the Main Page Component:

<div className="main-page">
 <div className="title">Main Page</div>
</div>

Style the component using CSS like this:

 .main-page .title{
  color:red;
 }

Apply similar styling techniques for other components by nesting CSS classes accordingly:

 .login-page .title{
  color:green;
 }

This method ensures that your CSS styles remain separate and do not get mixed up.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error: The npm-link library encountered an invalid hook call

Problem Description: I am working on developing a package named eformless. To set up the package, I utilized CRA to create a directory named sandbox where I linked the package. However, I keep encountering an error when attempting to launch the sand ...

CSS Transition - Troubleshooting my malfunctioning code

I seem to be facing a simple issue with my code. The following snippet does not work in Chrome or Firefox, as the transition property is not working properly. Instead of smoothly transitioning from blue to red when hovered over, the element immediately swi ...

Extract the entire div including all its elements and then transmit it using the PHP mail function

Currently, I am developing a feature that allows users to send an email. The email should include only one div from the page which contains elements added using the jQuery drag and clone function. I am unsure how to copy the entire div along with its child ...

Discover the Magic Trick: Automatically Dismissing Alerts with Twitter Bootstrap

I'm currently utilizing the amazing Twitter Bootstrap CSS framework for my project. When it comes to displaying messages to users, I am using the alerts JavaScript JS and CSS. For those curious, you can find more information about it here: http://get ...

Is it necessary to utilize the useState() function during the signup process, even when a defaultValue is not present?

Exploring the world of React I have embarked on a project to build a website using Next.js, and I am currently working on a signup page. Throughout most of the page, I have been utilizing useState to manage values and interact with APIs. However, I find ...

Tips for choosing and deselecting data using jQuery

Is there a way to toggle the selection of data in my code? Currently, when I click on the data it gets selected and a tick image appears. However, I want it so that when I click again on the same data, the tick will disappear. How can I achieve this func ...

What is the best approach to retain a user's selection for dark mode?

I have created a small website to showcase my work, but I'm struggling to figure out how to make the website remember a user's choice of dark mode. After searching on Stack Overflow, I came across suggestions like using cookies or localStorage. ...

Do all the data get stored in Next.js SSR caching or just the data that is returned?

Working with an API that offers pagination but lacks the ability to sort data according to client requirements, I had to come up with a workaround. My solution involves fetching all the data from the API within getServerSideProps and returning only a subse ...

Error: Import statement is not allowed outside a module while running on live server

//this is the Greetings.js file import React from "react"; function DisplayGreetings() { return ( <div><h1>Welcome</h1></div> ) } export default DisplayGreetings //This is the Main.js file import React,{Compone ...

Struggling to use GSAP to control the timeline with my custom functions

I'm attempting to create a greensock animated banner with the ability to switch between different scenes. I've made progress by setting up the timeline for each scene's intro and outro animations using the GreenSock API documentation. Howeve ...

Tips on eliminating the gap between the dropdown menu in Firefox browser

After testing in Chrome and seeing no issues, I noticed that the input field's position changes and there is spacing between the dropdowns when opening in Firefox. View in Firefox browser: https://i.stack.imgur.com/WYpuy.png View in Chrome browser: ...

Vuetify Container with a set maximum width that remains fixed

I recently started developing a web application using Vue.js and Vuetify (https://vuetifyjs.com/en/). Currently, I have a basic layout with 3 columns. However, I noticed that the width of these columns is restricted to a maximum of 960px due to some defau ...

What is the best practice for storing references to DOM elements in Reactjs?

class SearchInput extends React.Component { constructor(props) { super(props); this.searchInputRef = React.createRef(); // ...

Accordion symbol for adding or subtracting

Looking for a way to change the Toggle text in my angular 7 application accordion to images or content displaying a + sign for collapse and - for expand. I need to achieve this using CSS in my SCSS stylesheet so that I can later change the color of the sig ...

The vertical tabs in JQueryUI lost their functionality when a few seemingly unrelated CSS styles were added

Check out the JsFiddle demo here I embarked on a mission to craft JQueryUI Vertical tabs by following the guidance provided in this example. The source code within the aforementioned link contains specific CSS styles: .ui-tabs-vertical { width: 55em; } ...

What steps can you take to ensure that a recreated React component retains its state?

Within this sandbox demo, there is an example that may seem contrived but effectively makes a point. Upon clicking the "Add column" button, it should add a new column. However, it only works once and fails on subsequent attempts. Upon inspection of the lo ...

Components can be iterated over without the use of arrays

In my component, I have a render that generates multiple components and I need some of them to be repeated. The issue I am facing is that when I create an HTML render, the variable is not being processed and it just displays as text. Although the actual c ...

Safari shows a contrasting outcome

Having an issue with compatibility in the safari browser You can check out the site here: The problem lies with the text inside the image, I want it to display properly like it does in Chrome. Here is the desired result for Safari as well. Below is the ...

What is the reason border property does not transition effectively?

I am trying to remove the border property after a certain period of time (1 second) and make it smooth. Here is what I have attempted: var elem = $('div').css({'border-top':'6px solid #FC9A24', 'border-le ...