What is the best way to utilize multiple .css files on distinct components within a React application?

Working on a project with two separate .jsx files each representing a different component.

The first one is called Blog.jsx

import React from "react";
import '../assets/css/blog.css';

export const Blog = () => (
    <div>
        <h1>Hello Blog</h1>
    </div>
)

Accompanied by its own CSS file, blog.css

div { background: #ff481f; }

Then we have the second component, Landing.jsx

import React from "react";
import '../assets/css/landing.css'

export const Landing = () => (
    <div>
        <h1>Hello Landing</h1>
    </div>
)

With its corresponding CSS file, landing.css

div { background: #86ff2b; }

Upon implementing routing and adding instances of both components in the App.js file (the main file in a React application), an issue surfaced. When navigating between components, the background color remains the same for both (only loading the styles from landing.css).

How can I resolve this problem so that each component utilizes its respective CSS file correctly and loads it accordingly?

Answer №1

Typically, webpack and similar build tools will consolidate all CSS files into one, even when CSS is imported from separate JSX files. This means that using different CSS files may unintentionally impact other parts of the page.

To work around this issue, there are a few options available:

  1. Implement BEM for naming class names.
  2. Utilize cssModules. With cssModules, each element will have its own unique class name, minimizing the risk of styles affecting unintended elements unless the :global selector is used.

Answer №2

Avoid using html tags as css selectors, as it is considered a bad practice due to the described behavior.

It is recommended to use only css classes or inline styles. Using id's is also discouraged as they have high priority.

div {
  width: 20px;
  height: 20px;
}

#id {
  background: red;
}

.class {
  background: green;
}
<div id="id" class="class"></div>

When using css classes and encountering similar class names, consider utilizing css modules or css-in-js for resolution. BEM methodology can also be beneficial in such cases.

CSS modules will append a random hash to your classes, ensuring uniqueness and avoiding conflicts.

CSS-in-JS allows you to write styles with JavaScript, enabling dynamic styling based on requirements.

While pure CSS, SCSS, and PostCSS are options, many companies opt for either css modules or css-in-js for their projects.

BEM provides naming conventions for better organization of class names.

Lastly, when using inline styles in React, remember that {} constructs new objects on each call. To prevent unnecessary re-renders, define styles outside the component class.

Answer №3

Avoid defining your CSS using HTML tags as it can have a global impact on your application.

Instead, consider using className, id, or inline styling methods.

For example: App.css

.myApp { color: red; }
#myApp2 { color: blue; }

App.js

import './App.css'

<div className="myApp">Color changed by className</div>
<div id="myApp2">Color changed by id</div>
<div style={{color:'red'}}>Color changed by inline object styling</div> // inline styling

Answer №4

If you're looking to streamline your CSS imports/loads, this may not be the ideal solution for you.

However, if you prefer a quick fix without delving too deep into CSS, this method could work best for you while allowing you to continue working with HTML tags.

One approach is to add a div for each component, assign an ID to the div, and wrap the component within it. This way, in the component's CSS files, you can define all styles starting with the #ID selector to ensure that only the corresponding component is affected by the CSS classes or HTML tags.

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

Tips for adding a class to the output of a jQuery ajax request?

I've been searching for a solution to this issue without any luck. Below is the code I have: jQuery("#categories_parent_id").change(function() { id = jQuery("#categories_parent_id").val(); jQuery.ajax({ type: ...

Using PHP's header function to alter directories

So I am currently diving into PHP and facing a challenge with using headers. My setup involves using xampp for development purposes. I have a basic form where users can log in on "index.php". Upon successful login, the header function kicks in to redirect ...

Next.js allows for the wrapping of a server component within a client component, seamlessly

I am currently working on a project where I have implemented a form to add data to a JSON using GraphQL and Apollo Client. The project is built with TypeScript and Next.js/React. However, I am facing a conflicting error regarding server client components ...

The state variable hook fails to increase while in the closure

codesandbox.io/s/github/Tmcerlean/battleship I am currently working on the development of a simple board game and I am facing an issue with updating a state variable when a player clicks on a cell with a valid move. Despite having all the necessary funct ...

Is a backend necessary for my ReactJS web application?

Hey there! I am currently in the process of creating a front-end web application using ReactJS. My app will display various arrays of dogs, cats, and other animals, each with multiple properties and a couple of images. The user interface features a search ...

Having trouble accessing the `name` property of null when using the autocomplete feature in Material UI

I encountered an issue when I clicked on the clear cross button of an autocomplete feature using Material UI. Below is my AutoComplete code: <Autocomplete autoComplete fullWidth options={esp ...

Trouble with Two Divs Layout

My website layout includes links on the left side of the page within a floating div, with content on the right side in another floating div. However, I'm facing an issue where the content moves below the links when the page is resized. I attempted to ...

Aligning text at the center using bootstrap

I'm struggling with centering text within my website links, specifically in the navigation section "about me," "portfolio," "skills," and "contact." I've tried adding the text-center class and using the text-align function in the CSS, but nothing ...

The mysterious height phenomenon when setting the width of a list item with jQuery

Consider a basic ul and li setup similar to this: <div id="middle"> <ul> <li> <a> bridal </a> </li> //.... </ul> </div ...

utilizing a Bootstrap modal element throughout multiple HTML documents

I have a bootstrap modal dialog div that I want to use in all 4 html pages of my web application without repeating the code. I have a common JavaScript file for this purpose. What is the best way to achieve this? <!-- Modal --> <div class="modal ...

Tips for displaying a loading indicator above a form

I've been struggling to figure out how to display a loading indicator on top of my form without messing up the styling... https://i.sstatic.net/FFCRW.png My goal is to show the loading indicator when any action, like deleting an item or changing qua ...

Exploring the world of colored tab links in CSS

Check out this code: <!doctype html> <html lang="en"> <head> <meta charset="utf-8" /> <title>My Unique Page</title> <link rel="stylesheet" href="http://code.jquery.com/ui/1.8.3/themes/base/jquery-ui.css" /> ...

Is there a way to activate the final form when submitted?

I am facing an issue with React Final Form. Despite following the example in the official documentation, I am still struggling to understand why my form is not triggering the onSubmit function as in the example. I am also grappling with understanding the p ...

What is the process for creating a transparent default color theme in MUI?

I'm looking to make an element's background color the primary main color with some transparency using Material-UI. I've attempted a couple of methods, but unfortunately neither have worked for me. Any suggestions or guidance would be greatly ...

Is there a way to allow scrolling in only one direction using CSS?

I am facing an issue with resizing elements within a list. The requirement is that when the elements are resized, they should overflow the container only in the x direction. There must not be any scrolling in the x direction, but scrolling should be allowe ...

Interactive Map Using HTML5, CSS, and JQuery

As someone venturing into the world of web front end development, I am curious about the process of mapping an image so that specific functions can be triggered by pressing different parts. In this case, the shapes will be irregular (such as a map of Europ ...

Customizing font size in React with Material UI: A comprehensive guide on adjusting the font size of the Select component

I'm currently working on a web application that utilizes React along with Material UI. My goal is to adjust the font size of the Select component. I've attempted to achieve this by utilizing the MenuProps property, as shown in the following code ...

Select a division and retrieve the identification of a different division

I am looking to trigger an event by clicking on one element and extracting the ID from a separate, unrelated div. Here is my attempt: $(".map_flag").on("click",function(){ var selectedID = ($(this).attr("data_modal")); $("#" + selectedID).fade ...

Utilize the functionality of the acuityscheduling API to streamline your

I've experimented with various methods but haven't had any success. Hopefully, you guys can share some insight. I'm utilizing acuityscheduling's API to fetch appointments. According to their documentation, the process should look someth ...

React Query: obtaining the status of a query

In the realm of React Query, lies a valuable hook known as useIsFetching. This hook serves the purpose of indicating whether a particular query is presently fetching data. An example of its usage can be seen below: const queryCount = useIsFetching(['m ...