What's the reason for not being able to customize classes for a disabled element in Material-UI?

Currently, I am utilizing Material-UI to style my components. However, I am facing challenges when trying to customize the label class for disabled buttons. Despite setting a reference as "&$disabled", it does not yield the desired results.

import React from "react";
import { withStyles } from "@material-ui/core/styles";
import Button from "@material-ui/core/Button";

// By using the `withStyles()` higher-order component, a `classes`
// prop is injected and utilized by the `Button` component.
const StyledButton = withStyles({
  root: {
    background: "linear-gradient(45deg, #FE6B8B 30%, #FF8E53 90%)",
    borderRadius: 3,
    border: 0,
    color: "white",
    height: 48,
    padding: "0 30px",
    boxShadow: "0 3px 5px 2px rgba(255, 105, 135, .3)"
  },
  label: {
    "&$disabled": { backgroundColor: "blue", textTransform: "capitalize" }
  },
  disabled: {}
})(Button);

export default function ClassesShorthand() {
  return <StyledButton disabled>classes shorthand</StyledButton>;
}

If you want to explore more, here is a link to the codesandbox example: https://codesandbox.io/s/material-demo-7s9u3

Answer №1

You have identified two distinct issues:

  1. The placement of your &$disabled reference within the label class is causing a problem. The label class is applied to a span inside the button, whereas the disabled class needs to be on the button itself. This results in CSS with .MuiButton-label.Mui-disabled not matching anything. To resolve this, move &$disabled under root instead of label.
  2. Another issue exists in the definition of the background-image property within the linear-gradient in the root. You are only overriding the background-color, and when a background image is present, the color isn't visible. Therefore, for the disabled case, you'll need to remove the background image.
import React from "react";
import { withStyles } from "@material-ui/core/styles";
import Button from "@material-ui/core/Button";

// The `withStyles()` higher-order component injects a `classes`
// prop utilized by the `Button` component.
const StyledButton = withStyles({
  root: {
    background: "linear-gradient(45deg, #FE6B8B 30%, #FF8E53 90%)",
    borderRadius: 3,
    border: 0,
    color: "white",
    height: 48,
    padding: "0 30px",
    boxShadow: "0 3px 5px 2px rgba(255, 105, 135, .3)",
    "&$disabled": {
      backgroundImage: "none",
      backgroundColor: "blue",
      color: "rgba(255,255,255,0.6)",
      textTransform: "capitalize"
    }
  },
  disabled: {}
})(Button);

export default function ClassesShorthand() {
  return <StyledButton disabled>classes shorthand</StyledButton>;
}

https://codesandbox.io/s/disabled-button-background-veup6?fontsize=14&hidenavigation=1&theme=dark


If targeting the span within the button instead of the button itself is intentional, follow these steps (which focus on the label class as a descendant of the disabled class):

import React from "react";
import { withStyles } from "@material-ui/core/styles";
import Button from "@material-ui/core/Button";

// The `withStyles()` higher-order component injects a `classes`
// prop used by the `Button` component.
const StyledButton = withStyles({
  root: {
    background: "linear-gradient(45deg, #FE6B8B 30%, #FF8E53 90%)",
    borderRadius: 3,
    border: 0,
    color: "white",
    height: 48,
    padding: "0 30px",
    boxShadow: "0 3px 5px 2px rgba(255, 105, 135, .3)"
  },
  label: {
    "$disabled &": {
      backgroundColor: "blue",
      color: "rgba(255,255,255,0.6)",
      textTransform: "capitalize"
    }
  },
  disabled: {}
})(Button);

export default function ClassesShorthand() {
  return <StyledButton disabled>classes shorthand</StyledButton>;
}

https://codesandbox.io/s/disabled-button-background-on-label-p9md4?fontsize=14&hidenavigation=1&theme=dark

Answer №2

When working with Material-ui Button, it is important to note that there is a disabled css rule which should not be left as an empty object. Below is an example of how to properly style the button:

const StyledButton = withStyles({
  root: {
    background: "linear-gradient(45deg, #FE6B8B 30%, #FF8E53 90%)",
    borderRadius: 3,
    border: 0,
    color: "white",
    height: 48,
    padding: "0 30px",
    boxShadow: "0 3px 5px 2px rgba(255, 105, 135, .3)"
  },
  disabled: { background: "blue", textTransform: "capitalize" }
})(Button);

https://codesandbox.io/s/material-demo-59l32?fontsize=14&hidenavigation=1&theme=dark

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

Perhaps dividing numbers with regular expressions

My HTML textarea allows users to input numeric serial numbers in various formats - either inline, separated by any character, or in columns from an Excel file. The serial codes are either 14 characters long if the first character is "1," or always 15 char ...

Maximizing Efficiency: Sending Multiple Responses during computation with Express.js

Seeking a way to send multiple responses to a client while computing. See the example below: app.get("/test", (req, res) => { console.log('test'); setTimeout(() => { res.write('Yep'); setTime ...

Why isn't my JavaScript AJAX PHP if statement functioning properly?

I have been struggling with this issue for more than two hours now and cannot seem to find a logical solution. When I remove the If statement highlighted by --> this arrow, the alert() function works perfectly fine. It triggers when I simply use if(true) ...

Tips for using MatTableDataSource in a custom Thingsboard widget

After creating multiple custom Thingsboard widgets, I've discovered that I can access a significant portion of @angular/material within my widget code. While I have successfully implemented mat-table, I now want to incorporate pagination, filtering, a ...

Unable to utilize combined data types in React properties

In my theme.interface.ts file, I defined the following 2 types: type ThemeSize = | 'px' | '1' | '1/2' | 'full' | 'fit' type ThemeWidthSpecific = 'svw' | 'lvw' | 'dvw&apos ...

Modifying the Button style in the KeyboardDatePicker component from Material UI

I recently developed a website using Material UI, where all buttons are styled as "outlined" except for the Calendar in KeyboardDatePicker. The "ok" and "cancel" buttons in this dialog have the default appearance. After reviewing the API documentation (), ...

Displaying an element outside with reduced opacity using fabric js and controls placed above overlay

The property controlsAboveOverlay in Fabric.js is a boolean that, when set to true, will display the controls (borders, corners, etc.) of an object above the overlay image. The overlay image is an image that can be placed on top of the canvas. Currently, ...

What steps should I take to address the warning that says: "Unable to execute a React state update on a component that is unmounted"?

Issue: I've been experimenting with a fix similar to this one in my code, but I'm struggling to understand how it fits into my current implementation. My attempt to apply the solution to the updateDose function has not yielded any results. The a ...

The Bootstrap nav-tab functions perfectly on a local server, but unfortunately does not work when hosted remotely

UPDATE: Issue resolved so I have removed the Github link. It turns out that Github pages require a secure https connection for all linked scripts. Always remember to check the console! I encountered an unusual bug where the Bootstrap nav-tab functionality ...

Tips for correctly saving an array to a file in node.js express using fs module

I have been attempting to write an array to a file using node.js and angular for assistance, you can refer to the provided code in this question. Whenever I send the array, the file displays: [object Object],... If I use JSON.stringify(myArr) to send my ...

Incorporating smooth sliding animation to ng-repeat elements

Our team has developed a custom widget in ServiceNow that displays a row of icons and reveals or hides additional details in a div when icons are clicked. Below is the structure of our html and client controller: <div class="icons"> <ul class=" ...

The term "this" in the global scope versus within a function in the Node.js environment

console.log(this) // {} function abc(){ console.log(this) } abc() // global The concept of this can vary between the global space and inside a function in Node.js. console.log(this === module.exports) // true function abc(){ ...

When an element within a dropdown is hovered over, a dropdown menu is triggered

As a newcomer to Web Development, I am facing a fundamental issue with my bootstrap navigation bar. The navigation bar contains multiple dropdown buttons that activate on hover. One of the buttons within a dropdown needs another dropdown to appear when hov ...

The function GetURLParameter(sParam) is displaying %20 as blank space in the webpage

I am facing an issue with a code that pulls URL parameters into the landing page. The problem is that it is including white spaces as %20. For example, if my URL parameter is: example.com/?title=my website, it would display my%20website on the page inste ...

Discover the secret to displaying a "read more" link for p tag content in React once it surpasses a specific length!

{!post.isSearch && ( <p className="text-sm"> {post.postType == "post" ? post.content : truncate(post.content, { length: maxChars })} </p> ...

Please note: In React Material UI, Tabs can only accept Tab Components as children

When working with Material UI tabs, I encountered an issue where I received a warning that said: Warning: Tabs only accepts Tab Components as children. Found function (props, context, updater) { // This constructor gets overridden by mocks. The argumen ...

Revise the calculation output when a specific input is missing

As I work on creating a basic web page for computing values based on selected options, I've encountered an issue with the calculation process. The result does not immediately appear; instead, I have to input a value like 0 and then delete it in order ...

Ensuring that images are the perfect size for their parent container

Exploring the functionalities of angular bootstrap carousel, I am eager to showcase various images and enable clicking on them. The challenge I'm facing is that my images are not uniform in size and don't fit perfectly within my bootstrap column ...

What distinguishes defining a function through a prototype versus as a class property?

Check out this code snippet: Apple defines its function using a prototype. Banana defines its function using a class property. var Apple = function(){} Apple.prototype.say = function(){ console.debug('HelloWorld'); } var Banana = functio ...

Jest is not producing any output at all when executing tests

Below is a snapshot of my package.json: "jest": { "cacheDirectory": "/tmp/jestCache", "scriptPreprocessor": "node_modules/babel-jest", "modulePaths": [ "<rootDir>/app/static/react/" ], "moduleDirectories": [ "node_modules" ...