React can easily incorporate CSS from multiple components

I'm experiencing a CSS import issue in my React project. I have a "Home" page that imports Home.css and a "Hero" page that imports Hero.css. Strangely, the styles from Hero.css are being applied to every page in the application without me explicitly declaring it. How can I resolve this issue? Here are the components involved:

App:

import './App.css';
import { BrowserRouter as Router, Route, Routes } from "react-router-dom";
import Home from './pages/home/Home';
import Hero from './pages/hero/Hero';

function App() {
  return (
    <Router>
      <Routes>
        <Route path="/" element={<Home />}></Route>
        <Route path="/hero" element={<Hero />} ></Route>
      </Routes>
    </Router>
  );
}

export default App;

Hero:

import './Hero.css';

function Hero() {
    return <div>
        <h1>Hero!</h1>
        <button className='glow-on-hover' disabled>test 1</button>
        <button className='small-button glow-on-hover'>test 2</button>
        <button className='small-button glow-on-hover'>test 3</button>
    </div>;
}

export default Hero;

Hero.css:

div {
    height: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    justify-items: center;
    background-color: #002bff;
}

Home:

import './Home.css';

function Home() {
    return <div>
        <p>Home!</p>
    </div>;
}

export default Home;

Even though the Home.module.css file is empty, the div in the Home component is blue which is only declared in the Hero.module.css. How can I correct this?

Answer №1

It's crucial to recognize that including CSS in a JavaScript page is not a built-in feature of JavaScript itself; it instructs bundlers like Webpack to add the CSS during the build process.

Furthermore, CSS doesn't have inherent methods for limiting its effects to specific components. It's up to you to apply scoping through classes or other means.

For instance:

React

return <div className="component-hero">
  ...

CSS

.component-hero {
  ...
}

Edit:

Although the information above reflects the nature of CSS, there are tools available that can automate scoping with unique identifiers. Refer to other answers for more details.

Answer №2

Due to the lack of a built-in scoping mechanism in CSS Rules for specific components, this behavior is considered normal. As a result, all div elements within the component tree will be affected by this import.

To address this issue, I suggest using CSS Classes to create a layer of scope that is at least semantically meaningful.

<div className="hero-container">
  // nested jsx...
</div>

You can then define CSS rules in your hero.css file:

.hero-container {
  // css-rules
}

If you are using the create-react-app toolchain, there is a feature called CSS Modules. For more information on CSS Modules, refer to the official documentation here.

Since all CSS is bundled into a single index.css file in the end, maintaining distinct class names can become challenging in larger projects. Therefore, it is advisable to consider using solutions like CSS Modules or third-party libraries such as styled-components, which style our components in a more tightly coupled manner.

Answer №3

When you import CSS globally using import './Home.css';, it applies the styles globally. If you want to apply CSS styles locally to a component, there are different options available.

Option 1: You can use module.css files where all class names and animation names are scoped locally by default. This means you can declare styles using classes but not IDs. Here's an example:

.home {
  background: green;
}

You can then import this into your JSX file and apply the class like this:

 import homeStyles from './home.module.css';
 
 export const Home = () => {
   return (
     <section className={homeStyles.home}>
       Example of module.css
     </section>
   );
 };

In this code snippet, homeStyles is an object that contains the home class property for styling the section element.

Option 2: Another option is to use Styled Components, which is a third-party library with extensive resources for styling components. Material-UI V5 also uses this styling pattern. Here's an example:

import styled from "styled-components";

const SectionWrapper = styled.div`
  .home {
    background: green;

    @media screen and (max-width: 600px) {
      background: red;
    }
  }
`;

export const Home = () => {
  return (
    <SectionWrapper>
      <div className="home">Example of styled-component</div>
    </SectionWrapper>
  );
};

In styled components, you can also use media queries like in module.css. The example above shows how the background color changes to red when the screen size is less than 600px. For more information, visit the official site.

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

Failure to update values in local storage using the React useLocalStorage hook

I've developed two unique custom hooks named useLocalStorage and useAuth. function getDefaultValue<T>(key: string, initialValue: T | null): T | null { const storedValue: string | null = localStorage.getItem(key); if (storedValue) { retur ...

Scrolling automatically to a DIV is possible with jQuery, however, this feature is functional only on the initial

I'm currently working on a Quiz site and I've encountered a puzzling issue. Since the explanation only appears after an answer is selected - essentially a "hidden" element, I decided to wrap that explanation into a visible DIV. The code I'v ...

Having trouble with Bootstrap 5 sticky-top functionality within a container?

Why is my <nav> not sticking to the top of the viewport when scrolling, even though it has the .sticky-top class? <!doctype html> <html lang="en"> <head> <meta charset="utf-8> <meta name="viewport" content="wi ...

What could be causing issues with my application when using server-side rendered styled-components with Next.js?

I am in need of assistance with an error I've encountered. Every time I try to access the homepage of my Next.js app, it breaks and displays a cannot read data map of undefined error. The browser consistently directs me to the _document.js file, but I ...

Creating a form in NextJS with the App Router: A step-by-step guide

When it comes to creating forms with the Pages Router in Next.js, the official approach is quite clear. However, this isn't the case with the App Router. Initially, one might consider using a POST Router handler, but the documentation warns: Note: ...

Having trouble getting the hover effect to work when selecting a different section of the SVG

In my SVG checkbox design, I have a circle element surrounding a polyline element (which acts as the checkmark). The boundaries of the icon extend beyond the circle, causing hover styles to trigger even when hovering outside the circle. I want to change st ...

What is the method for displaying all pages within a specified path?

My current setup looks like this: pages: - route1 - lots of js page - index.js I want to list all the pages under route1 on my index page. How can I retrieve a list of available pages? I attempted to use getStaticProps in the index file to load ...

What is the optimal method for allowing users to modify the website name and various frontend settings in a ReactJS environment?

Developing a blog web application using nodejs, reactjs, and mongodb. Implementing a feature where admin users can customize their blog's name, color scheme, header image, sidebar image, and content without developer intervention. To start with, focus ...

Expandable full-width JavaScript accordion for seamless navigation

Currently, I am working on a simple on-page JavaScript application that consists of multiple data pages within one main page. My goal is to create a horizontal accordion effect where clicking on headers on either side will smoothly switch between the diffe ...

The scrollbar on the side of my page seems to be malfunctioning

I'm having an issue with the collapsible sidebar and tabs on my angularjs page. The scroll bar is not appearing when there is overflow in the sidebar. I've tried setting the scrollbar height to auto and overflow-y to scroll, but it's not wor ...

Updating object property values within an array: A step-by-step guide

const alternateData = [ { value: 1, label: "altDesc1" }, { value: 2, label: "altDesc2" }, { value: 3, label: "altDesc3" }, { value: 4, label: "altDesc4" }, { value: 5, label: "altDesc5" }, { value: 6, label: "altDesc6" } ]; cons ...

Instructions for extracting and storing values from a JSON response into an array

Utilizing react-select async feature to fetch options from an input provided via an API. The JSON response contains a list with a "FullName" field, which I aim to extract and store in an array to be used as options. Within the JSON structure, there is a l ...

Tips to prevent elements from overlapping in Angular applications

I am facing an issue with my Angular-based app where I dynamically populate the page with table rows. There is an app-console element below the page that has a fixed position. Whenever I click the button to add a new row, it overlaps with the app-console. ...

Left-align elements within a div container that is centered

I want to left-align my elements within a div container that is centered. I used the text-align property to center the overall div, but now I'm having trouble aligning another content container's text to the left within the center-aligned div. H ...

The demonstration of using React in conjunction with Next.js is currently experiencing technical difficulties

My Package Configuration: { "name": "nextjs", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "dev": "next", "build": "next build", "prod_start": "NODE_ENV=production node server.js", "start": "next start" ...

The component prop of Typography in TypeScript does not accept MUI styling

Working with MUI in typescript and attempting to utilize styled from MUI. Encountering an error when passing the component prop to the styled component. The typescript sandbox below displays the issue - any suggestions for a workaround? https://codesandbo ...

The animation of the background color over an image appears glitchy when viewed on Safari

I've been attempting to create an animation that changes the background color over an image. Everything seems to be working fine on all browsers and operating systems except for Safari on macOS. I've searched extensively on SO and Google but have ...

How can I dynamically assign @ViewChild('anchor_name') to a newly updated anchor element in Angular 2+?

Upon receiving an item through a GET request, I set the item_id upon subscription. In the HTML file, I create a div with an anchor id="{{this.item_id}}". However, I encountered the following error: FeedComponent.html:1 ERROR TypeError: Cannot read propert ...

What is the best way to retrieve a GWT textbox value using Selenium WebDriver?

I'm currently testing my GWT application with selenium, and the HTML generated by GWT Textbox appears like this: <input type="text" class="gwt-TextBox" > Even though there's no value visible in the code above, I can see text in the UI. Is ...

Disable automatic focusing for a material-ui popover component

I am struggling to create a search match list that updates as the user types in their query. However, I am facing an issue where the input element loses focus to the pop-up. I have attempted to programmatically set the focus using refs, but I am unable to ...