The Material UI button feature neglects to account for custom CSS styles when attempting to override the default settings

Utilizing a custom bootstrap css styles in my react app, I am seeking to enhance the default material ui components with the bootstrap styles.

import React, {useState} from 'react';
import 'cg-bootstrap/core/build/cg-bootstrap-standard.css'

const Sample = () => {
const [value, setValue]= useState('');

const handleChange = (e:React.ChangeEvent<HTMLInputElement> ) => {
        setValue(e.target.value);
    }
return (
<Grid container justify="center" alignItems="center">

<Grid item>
<Typography>Label text</Typography>
</Grid>
<Grid item>
<TextField value={state.value} variant="contained" onChange={handleChange}/>
</Grid>
<Grid item>
<Button 
variant="contained"
type="submit"
classes={{
contained: "btn btn-md btn-primary",
}}>
Submit
</Button>
</Grid>
</Grid>
)
}

cg-bootstrap-standard.css

.btn-primary {
  color: #fff;
  background-color: black;
  border-color: black; }
  .btn-primary:hover {
    color: #fff;
    background-color: black;
    border-color: black; }
  .btn-primary:focus, .btn-primary.focus {
    color: #fff;
    background-color: black;
    border-color: black;
    -webkit-box-shadow: 0 0 0 0.125rem rgba(38, 38, 38, 0.5);
    box-shadow: 0 0 0 0.125rem rgba(38, 38, 38, 0.5); }
  .btn-primary.disabled, .btn-primary:disabled {
    color: #fff;
    background-color: black;
    border-color: black; }
  .btn-primary:not(:disabled):not(.disabled):active, .btn-primary:not(:disabled):not(.disabled).active,
  .show > .btn-primary.dropdown-toggle {
    color: #fff;
    background-color: black;
    border-color: black; }
    .btn-primary:not(:disabled):not(.disabled):active:focus, .btn-primary:not(:disabled):not(.disabled).active:focus,
    .show > .btn-primary.dropdown-toggle:focus {
      -webkit-box-shadow: 0 0 0 0.125rem rgba(38, 38, 38, 0.5);
      box-shadow: 0 0 0 0.125rem rgba(38, 38, 38, 0.5); }

Upon inspecting the chrome console, the https://i.stack.imgur.com/kCJOw.png

https://i.stack.imgur.com/HpArG.png

https://i.stack.imgur.com/OtOaq.png

The styles of btn btn-primary were overridden and I want to ensure that their styles are the final ones applied to the button rather than the default styles of material-ui. How can I resolve this issue?

Answer №1

To optimize your styles, utilize the StylesProvider component along with the injectFirst prop

The StylesProvider component includes an injectFirst prop to prioritize injecting style tags at the beginning of the head section

import { Button, StylesProvider } from "@material-ui/core";

function Sample() {
  return (
    <StylesProvider injectFirst>
      {/* Your component tree */}
      <Button
        variant="contained"
        classes={{ contained: "btn btn-md btn-primary" }}
      >
        Hello
      </Button>
    </StylesProvider>
  );
}

By default, MUI appends its style sheets at the end of the <head> tag, resulting in higher priority than external styles like Bootstrap. Using the above approach should resolve any conflicts.

https://material-ui.com/styles/advanced/#css-injection-order

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

Steps for accessing CSS variables within a scoped style block in Vue with Buefy_integration

After diving into the Buefy documentation, I successfully personalized my color scheme and even crafted unique hues by applying the is-[colorName] as a class to HTML elements. <style lang="scss"> // Importing Bulma's core @import "~bulm ...

Implementing a feature that loads older posts on a webpage as users scroll down

Spent hours trying to get my site to automatically load older posts on scroll down with no luck. Any assistance is greatly appreciated :) After researching, [this tutorial][1] seemed like the best solution so I followed it step by step and integrated ever ...

Sporadic UnhandledPromiseRejectionWarning surfacing while utilizing sinon

Upon inspection, it appears that the objects failApiClient and explicitFailApiClient should be of the same type. When logging them, they seem to have identical outputs: console.log(failApiClient) // { getObjects: [Function: getObjects] } console.log(expli ...

Tips for transferring data between two forms in separate iFrames

I'm trying to achieve a functionality where the data entered in one form can be submitted to another form within an iframe. The idea is to allow visitors to preview their selected car in the iframe, and if satisfied, simply press save on the first for ...

Conflicting styles arise when using the makeStyles function from Material UI with imported

In working on a React component library using create-react-library, I have incorporated basic components that utilize Material UI components and the material UI hook-based styles pattern. For example (in a simplified form): // LibraryComponent.js const u ...

Waiting for the response to come by subscribing in Angular

I am encountering an issue while trying to subscribe to an Observable and assign data from the response. The problem is that my code does not wait for the response before executing the console.log(this.newIds) line, resulting in an empty value being logg ...

In an HTML document, you may encounter whitespace that is not present in JSFiddle

Upon running this HTML file in my browser, I noticed that there is an 18px gap at the top of the first div. It's strange because this issue only occurs when I run the HTML locally on my browser, but everything works fine on JSFiddle. I'm puzzled ...

Position the background in CSS according to the class name

There are a total of 8 icons, with 4 in blue and 4 in grey. Therefore, product 1 has both a blue icon and a grey icon. When the user has product 1, they will see the blue icon (with an added class on the container called .gotProduct), and when they don&ap ...

Installing a specific version of yarn on Ubuntu

Is there a way to install yarn version 0.27.5 in Ubuntu despite the fact that the latest update is for version 1.2.1? ...

Calculator for Angular User Input

Looking to create a simple application, I encountered an issue with my if statement. I would greatly appreciate any help in identifying the problem. The goal of the application is to provide users with a text box where they can input comma-separated items ...

Discovering user activity through rooms within SocketIO

My goal is to trigger an event when a user switches between online and offline status. The challenge arises from the fact that a user may have multiple tabs open, making it ineffective to track their connection status using on('connect') and on(& ...

Defining the structure of an object using a type interface

I am having trouble identifying the issue with this type declaration in relation to the interface. When using TypeScript, I encountered an error message stating: "State is an unresolved variable". Does anyone have insights on why this might be considered ...

"Exciting Changes in Color According to the Active State of vue-route-link

I am trying to find a way to customize the CSS based on whether a link is exact or active. Essentially, when a user clicks on a menu item, I want the underline to change depending on whether the link is an active router-link. Although I was able to accompl ...

bypassing files in mongodb for paging purposes

I need to retrieve specific documents based on the page count parameter in my GET request. For instance, when I send a GET request to http://localhost:3001/posts?page=2, I want to receive 10 documents per page starting from document 10 to 20. router/posts ...

Guide on uploading an image file through ReactJS to an api integrated with NestJS utilizing the bytea datatype

I'm seeking guidance on how to correctly upload a file using ReactJS to an API built with NestJS. Here's what I have accomplished so far: In the API's swagger documentation, there is a post method specified for file uploads. Below is the t ...

The parameter cannot be assigned a value of type 'string' as it requires a value that matches the format '`${string}` | `${string}.${string}` | `${string}.${number}`'

I recently updated my react-hook-forms from version 6 to version 7. Following the instructions in the migration guide, I made changes to the register method. However, after making these changes, I encountered the following error: The argument being pass ...

jQuery alert: A TypeError was caught stating that the object being referred to does not have the 'dialog' method available

For a few days now, I have been tirelessly searching for a solution to this issue and it has caused me quite a bit of stress. My problem lies in echoing a JQuery popup script within php: echo '<link rel="stylesheet" href="http://code.jquery.c ...

Socket.io in Express is already assigned to another address

I'm having trouble getting my app to connect with Socket.io via websockets. Each time I attempt to run this code snippet, I encounter the following error: Error: listen EADDRINUSE: address already in use :::3000 Despite checking for any other process ...

Issue encountered while attempting to retrieve data from a local json file due to Cross-Origin Resource Sharing

I'm attempting to fetch and display the contents of a JSON file on a webpage, but I'm encountering this error message: Access to XMLHttpRequest at 'file:///C:/Users/bobal/Documents/htmlTry/myData.json' from origin 'null' has ...

How can JavaScript be utilized to disable the use of the spacebar?

I have implemented a live search feature on the website I'm working on. Currently, the search function queries the MySql database as soon as the first character is entered and updates the results with each subsequent character input. However, I'v ...