Utilize CSS exclusively within a specific React component

Objective :

  • I need to apply the complete bootstrap CSS to a single react component without affecting other components. However, other components also depend on bootstrap and use bootstrap classes.
  • Is there a way to achieve this without modifying the classes/ids used in the component and ensuring that the CSS is specific only to that component? This may not be ideal from a programming standpoint, but any workaround would suffice.
    • If it's not possible, what are the minimal changes I can make to make it work? The code is extensive, so manually checking each division for CSS and adding an ID is not feasible at this point - considering it as a last resort solution.

Situation :

  • I have 2 components with lengthy code - let's call them Component A and B.

  • Component A includes:

    <link rel="stylesheet" href="assets/scss/style.css"> 
    <link rel="stylesheet" href="assets/css/bootstrap.min.css">

  • Component B includes:

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

Both components conflict with each other - using A damages B's CSS and vice versa.

Answer №1

When utilizing bootstrap as a global CSS, the styling will cascade throughout your project.

If you also want to incorporate webpack and have a mix of global CSS and component-specific CSS, you can configure webpack to apply CSS modules to files with a *.module.css extension and treat regular *.css files as global styles. Keep in mind, there may still be some manual overrides necessary.

Implementing this setup with webpack might seem daunting, especially for larger code bases.

Here's a basic approach on how to set up webpack for this scenario:

webpack.config.js

{
  test: /\.css$/,
  include: [/\.global/, /bootstrap/],
  loader: ExtractTextPlugin.extract({
    fallback: 'style-loader',
    use: [
      {
        loader: 'css-loader',
        options: { modules: false }
      }
    ]
  })
},
{
  test: /\.css$/,
  exclude: [/\.global/, /bootstrap/, /node_modules/],
  use: ExtractTextPlugin.extract({
    fallback: 'style-loader',
    use: [
      {
        loader: 'css-loader',
        options: {
          modules: true,
          localIdentName: '[local]--[hash:base64:5]'
        }
      }
    ]
  })
}

For more detailed information, check out the ongoing discussion and open PR at css-modules repository

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

Display the image on the right side when a specific number of pixels are available

Looking to have text wrapped around an image? Using float:right; can do the trick. However, is it possible to only float the image to the right when there is more than 200px of space available? For example: _____ |img | | | |_ ...

Inject Angular 2 component into designated space

I am working on a website that requires a settings dialog to be loaded in a designated area upon clicking a button. The settings dialog is a component that retrieves data from REST endpoints. I am hesitant to simply insert the component and hide it as I ...

I am encountering difficulties adding an array to Firebase due to the lack of asynchronous nature in Node.js

As a beginner in the world of nodejs, angularjs and firebase, I am encountering issues related to the asynchronous nature of nodejs while trying to load data into firebase. My goal is to search an existing list in firebase, add a new element to it, and wri ...

Use Django, Ajax, and Jquery to incrementally add items to a "cart" by selecting checkboxes one by one

Despite adding new code, it's still not working as expected... I've been attempting to implement a feature where users can select items using checkboxes and add them to the "cart" displayed at the top of the page. Each item on the page has a che ...

Utilizing Vue.js to incorporate the isActive property to the class name within a v-for loop, along with implementing dynamic class names

I am currently using a loop to iterate through some data in my store.js file, and everything is functioning as expected. However, I would like to add a condition to check if the Vue instance is active before applying a specific class to the polygon element ...

Utilizing $rootScope in AngularJS as a central data repository

I've come up with an idea for my AngularJS app and I'm curious to know what the AngularJS community thinks about it. Essentially, I'm connecting to a data API and displaying the results on the page. My approach involves creating an AngularJ ...

Tips for addressing the issue - error TS2451: Unable to redefine block-specific variable 'total'

I am currently working on setting up the Jest testing framework and running a basic test (using an example from jestjs.io). Here is the content of the sum.ts file: function sum(a: any, b: any):any { return a + b; } module.exports = sum; And here is the ...

In search of assistance to update a list during the creation of a Windows 8 application with HTML, CSS, and AngularJS, all powered

I'm currently working on an app that acts as a virtual warehouse, keeping track of item balances. After experiencing the challenges of using WinJS in comparison to AngularJS, I decided to combine both frameworks for my project. Adding and deleting i ...

What is the best way to integrate a CSS designed flag in my website's top navigation bar?

My goal is to make my website multilingual, allowing users to switch between languages using flags in a dropdown menu. Initially, I tried creating the flag images solely with CSS for better resizing ability but faced difficulties. So, I resorted to using s ...

Ways to verify if a user is authenticated in Firebase and using Express/Node.js

How can I determine if a user is authenticated to access a page that requires authentication? I attempted to check with (firebase.auth().currentUser !== null) but encountered an error: TypeError: firebase.auth is not a function This is my current configu ...

Arrange content within DIVs using Bootstrap-4

I'm having trouble figuring out how to align and organize my div content using Bootstrap. I'm a bit confused about how it all fits together align-items- * text-* align-self- * justify-items- * justify-self- * I'm attempting to structure my ...

Guide on implementing asyncWithLDProvider from Launch Darkly in your Next.js application

Launch Darkly provides an example (https://github.com/launchdarkly/react-client-sdk/blob/main/examples/async-provider/src/client/index.js) showcasing how to use asyncWithLDProvider in a React project (as shown below). However, I'm struggling to integr ...

Utilizing the bootstrap grid system, we can arrange three tables horizontally in

Can someone help me figure out how to print 3 tables per row on a page using the bootstrap grid layout? Currently, all tables are being printed vertically. Here is the code snippet: foreach($allmonths as $ind){ echo "<table>"; //echo "res ...

Creating a delete functionality button in JavaScript is essential for removing elements from a webpage with ease. This button allows users to seamlessly

I am currently working on an HTML form and here is the code for it: <div id="format"> <form id="myForm" onsubmit="myForm(event)"> <b>Name:</b></br> <input type="text" name="name" id="name" r ...

Transforming the MVC model attribute into an HTML attribute

Is there a way to include model attributes in the HTML input tag? Code [Required] [StringLength(20)] public string Username { get; set; } [Required] [StringLength(20)] [DataType(DataType.Password)] public string Password { get; set; } Expected Output: ...

Tips for managing Typescript Generics while utilizing the styled function provided by the '@mui/material/styles' package

import Table,{TableProps} from 'my/table/path' const StyledTable = styled(Table)({ ...my styles }) const CustomTable = <T, H>(props: TableProps<T, H>) => { return <StyledTable {...props} /> } This is the issue I encoun ...

Insert form onto a new line within the navigation bar

I have implemented this code for the following: - Add search form to a new line in small or smaller screen sizes. - Float the toggle button right in small or smaller screen sizes. The main issue is that the text input does not expand when the screen siz ...

Sails encountering CORS preflight error due to cross-origin request

I am new to creating hybrid apps and have been following some tutorials. However, I encountered these errors on my browser console: Refused to load the script 'http://192.168.1.142:35729/livereload.js?snipver=1' due to Content Security Policy di ...

Updating npm dependencies with unmet peer requirements

Having trouble updating react-router-dom, encountering an ERR with the error message ERESOLVE unable to resolve dependency tree. Attempting to update using the command: npm update "popper.js" "bootstrap" "react-router-dom" Could not resolve dependency: np ...

Eliminate specific content from within a div tag

Looking for a solution with the following HTML. <div id="textDiv"> <p> MonkeyDonkey is not a bird. Monkey is an animal. </p> </div> In this case, I am trying to delete the word "Donkey". I attempted the code below but it did no ...