Modify the color or background color of a disabled Material UI checkbox

The disabled unchecked checkbox appears too subtle to me, and I would like to enhance it by giving it a grey background and changing the cursor style to not-allowed.

I've been trying to implement these styles on the checkbox using the makeStyles, but so far without success. Here's my current code snippet:


const useStyles = makeStyles((theme) => ({
  disabledCheckbox: {
    cursor: 'not-allowed',
    color: 'grey',
    backgroundColor: 'grey',
  },
}));

// ...

const App = () => {
  const classes = useStyles();
  return (
    <div>
      Disabled:
      <Checkbox
        disabled={true}
        name="Disabled checkbox"
        classes={{ disabled: classes.disabledCheckbox }}
      />
    </div>
  );
};

Unfortunately, my attempts have not resulted in any visible changes, and the appearance of the disabled checkbox remains unchanged. You can compare a functional and non-functional version in this demo app.

What could be causing this issue? How can I successfully modify the background color of an unselected MUI disabled checkbox?

Answer №1

Using only the disabled class is not specific enough to override the default styles in IconButton. It's important to avoid changing the background-color for the entire checkbox as it will impact the hover effect area. Instead, target just the icon within the checkbox (although this may not be perfect).

The following code provides a way to define styles with the necessary specificity to focus on the icon. Overriding the cursor requires additional steps due to Material-UI disabling pointer events on disabled buttons. The CSS below re-enables pointer events but also turns off the hover effect previously blocked by 'pointerEvents: none'.

const useStyles = makeStyles((theme) => ({
  backgroundColorOnWholeIcon: {
    '&.Mui-disabled': {
      pointerEvents: 'auto',
      '&:hover': {
        backgroundColor: 'transparent',
      },
      cursor: 'not-allowed',
      '& .MuiSvgIcon-root': {
        backgroundColor: '#eee',
      },
    },
  },
}));

Unfortunately, there might still be issues with bleeding colors beyond the checkbox icon box dimensions. To address this, you can create a custom icon with an inner box that can be targeted separately via CSS.

The code snippet below shows how to create and target the inner box of the custom icon:

import React from 'react';
import createSvgIcon from '@material-ui/icons/utils/createSvgIcon';

export default createSvgIcon(
  <>
    <path d="M19 5v14H5V5h14m0-2H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2z" />
    <path fill="none" class="innerBox" d="M19 5v14H5V5h14" />
  </>,
  'CustomUnchecked'
);

To further style and customize your checkboxes, the provided example showcases using both makeStyles and themes for styling and theming purposes.

https://codesandbox.io/s/disabled-checkbox-x6mf2?fontsize=14&hidenavigation=1&theme=dark

Answer №2

Customizing the appearance of checkboxes can be achieved by passing checked and unchecked icons as styles. To change the style of a disabled checkbox, select the icon first and then utilize 'input:disabled ~ &' CSS selector. Below is an example of how styling can be applied:

const useStyles = makeStyles({
  root: {
    '&:hover': {
      backgroundColor: 'transparent',
    },
  },
  icon: {
    borderRadius: 3,
    width: 16,
    height: 16,
    boxShadow: 'inset 0 0 0 1px rgba(16,22,26,.2), inset 0 -1px 0 rgba(16,22,26,.1)',
    backgroundColor: '#f5f8fa',
    backgroundImage: 'linear-gradient(180deg,hsla(0,0%,100%,.8),hsla(0,0%,100%,0))',
    '$root.Mui-focusVisible &': {
      outline: '2px auto rgba(19,124,189,.6)',
      outlineOffset: 2,
    },
    'input:hover ~ &': {
      backgroundColor: '#ebf1f5',
    },
    'input:disabled ~ &': {
      boxShadow: 'black',
      background: 'rgba(0,0,0,0.5)',
    },
  },
  checkedIcon: {
    backgroundColor: '#137cbd',
    backgroundImage: 'linear-gradient(180deg,hsla(0,0%,100%,.1),hsla(0,0%,100%,0))',
    '&:before': {
      display: 'block',
      width: 16,
      height: 16,
      backgroundImage:
        "url(\"data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3E%3Cpath" +
        " fill-rule='evenodd' clip-rule='evenodd' d='M12 5c-.28 0-.53.11-.71.29L7 9.59l-2.29-2.3a1.003 " +
        "1.003 0 00-1.42 1.42l3 3c.18.18.43.29.71.29s.53-.11.71-.29l5-5A1.003 1.003 0 0012 5z' fill='%23fff'/%3E%3C/svg%3E\")",
      content: '""',
    },
    'input:hover ~ &': {
      backgroundColor: '#106ba3',
    },
  },
});

Check out the sandbox below for more examples.

https://codesandbox.io/s/material-demo-l8tq7?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

Searching the Google Place API to generate a response for dialogflow

I am currently facing an issue while trying to utilize the Google Place API for retrieving details to display a map (by fetching coordinates) and location information (address) as a response from my chatbot. I have created this code snippet, but encounteri ...

send back the result to the primary function

I need help with this code. I'm trying to return the budget from callbacks in the main function. How can I return a value from the main function? // This method returns the current budget of the user getCurrentBudget: function (req) { var reqTok ...

What is the best way to explain the concept of type indexing in TypeScript using its own keys?

I'm still learning TypeScript, so please bear with me if my question sounds basic. Is there a way to specify the index for this type so that it utilizes its own keys rather than just being an object? export type TypeAbCreationModal = { [index: stri ...

node.js: The Yahoo weather jQuery plugin fails to display any data

After successfully implementing node.js with jQuery and the plugin from , I now aim to utilize the weather data for a different purpose rather than directly inserting it into the HTML. However, I am encountering difficulties in accessing or displaying the ...

Tips on incorporating a personalized components directory into your Gatsby project

I am looking to integrate some custom React components from a GitHub repository into my Gatsby project. However, I am unsure about how to include an external folder. The structure of the components folder that I want to incorporate is as follows: |-- /dis ...

Utilizing Typeahead for Autocomplete in Durandal: A Step-by-Step Guide

I am attempting to implement an autocomplete input field with typeahead (Twitter Bootstrap) in a modal, but I am encountering difficulties making it function properly. Additionally, this autocomplete field needs to be observable with Knockout so that selec ...

NodeJS error: Attempted to set headers after they have already been sent to the client

As a beginner, I have encountered an error message stating that the API is trying to set the response more than once. I am aware of the asynchronous nature of Node.js but I am struggling to debug this issue. Any assistance would be greatly appreciated. rou ...

Setting the child elements of a CSS div to have the same width and be larger than the

Welcome everyone to my inaugural post! I hope I've followed the right steps. I'm encountering an issue where I have child divs that need to have equal widths. The #content can sometimes exceed the browser window's width (hence the 3000px), ...

The AJAX request is not triggered before the postback when using a LinkButton in ASP

I am facing an issue with running an insert statement using a button in my application. Although it is functional, I have noticed that whenever I click the button, the Page_Load function runs before the ajax statement executes. How can I ensure that the a ...

Increase the gap between MUI Select components vertically

Working on implementing MUI to create a vertical stack of Select components, I noticed that they are displayed without any spacing between them: https://i.stack.imgur.com/yBDO4.png The group is enclosed within a Box and each control follows this structur ...

I encountered an issue while trying to integrate react-alert into my React application. An Uncaught Error was thrown, stating that objects are not valid as a React

I encountered the following error: react-dom.development.js:14748 Uncaught Error: Objects are not valid as a React child (found: object with keys {$$typeof, render}). If you meant to render a collection of children, use an array instead. in Unknown (c ...

Can someone help me identify the issue with my JavaScript code?

Recently, I attempted to transfer data from JavaScript to HTML using Angular. Here is the code snippet: phonecatControllers.controller('start', ['$scope', function($scope){ $scope.lloadd=true; console.log('data - '+$ ...

Mastering APIs and Harnessing their Power

I am currently working on a project involving React and Express. In the backend, I have created a small API that streams information on my /API/ routes in the form of a JSON object. However, I am unsure how to display this information on the front end an ...

Sorting of dates in mui-datatables is not accurate

I have dates that are formatted using moment.js, for example ("Sat, Feb 22, 2020 12:55 PM") I retrieve them from firestore, and they appear to come in correctly as I first sort them in descending order. forms.sort(function(left, right) { return moment.u ...

Creating a straightforward Theme Changer feature using Vue.js

Check out this tutorial for creating a simple Dark/Light theme switcher using Tailwind CSS. This tutorial utilizes vanilla JS and only requires a single app.js file. If I want to incorporate this into a Vue project, should I simply paste the code into ~/s ...

Improper Alignment of Bootstrap 4 Navbar Link: Troubleshooting Required

Take a look at the image for the issue: https://i.stack.imgur.com/u9aCy.png As shown in the image, the NavBar links are stacked instead of being displayed in one row. This is the HTML code I have used: <!doctype html> <html> <head> ...

What could be causing this jQuery color picker to malfunction when used inside a Bootstrap modal?

Currently, I am utilizing the fantastic jQuery color picker provided by Although it functions as expected in "normal" scenarios, I have encountered an issue where the picker fails to display when the input parent element is nested within a Bootstrap 3 mod ...

Is it possible to capture "global" events while handling nested iframes?

My dilemma involves capturing a keypress event, but the user can potentially be navigating through multiple layers of iframes nested within each other. Initially, I attempted to add the event listener to the document, only to realize that it wouldn't ...

Is there a way to incorporate the information from PHP files into the output produced by JavaScript?

I am currently working on a JavaScript script that scrapes data and displays the result on the screen successfully. However, I now face a challenge in wrapping this output with pre and post content from PHP files for formatting purposes. Here is an overvi ...

Display a concealed text box upon clicking BOTH radio buttons as well as a button

Below is the HTML code for two radio buttons and a button: <body> <input data-image="small" type="radio" id="small" name="size" value="20" class="radios1"> <label for=&qu ...