Overriding MUI Chip deleteIcon color

Viewed 2758

I am trying to give custom color to deleteIcon of Chip component (MUI v5). As I can see, my styles are overridden by .css-inlzrk-MuiButtonBase-root-MuiChip-root .MuiChip-deleteIcon , but I could not override it. I don't want to give inline styles (eg. <Cancel style={{color: 'blue'}} />).

enter image description here

enter image description here

import * as React from "react";
import Chip from "@mui/material/Chip";
import Stack from "@mui/material/Stack";
import { makeStyles } from "@mui/styles";

import Cancel from "@mui/icons-material/Cancel";

export default function DeleteableChips() {
  const classes = makeStyles((theme) => ({
    icon: {
      color: "blue"
    }
  }))();

  const handleDelete = () => {
    console.info("You clicked the delete icon.");
  };

  return (
    <Stack direction="row" spacing={1}>
      <Chip
        className={{ deleteIcon: classes.deleteIcon }}
        label="Deletable"
        onDelete={handleDelete}
        deleteIcon={<Cancel className={classes.icon} />}
      />
      <Cancel className={classes.icon} />
    </Stack>
  );
}

CodeSandbox : https://codesandbox.io/s/deleteablechips-material-demo-forked-d6jq5?file=/demo.js

3 Answers

You can do it like this.

const classes = makeStyles((theme) => ({
    icon: {
      "&.MuiChip-deleteIcon": {
        color: "blue"
      }
    }
}))();

You can take a look at this sandbox for a live working example of this usage.

You should not use makeStyles or anything from the @mui/styles package in v5. From the docs:

@mui/styles is the legacy styling solution for MUI. It is deprecated in v5. It depends on JSS as a styling solution, which is not used in the @mui/material anymore. If you don't want to have both emotion & JSS in your bundle, please refer to the @mui/system documentation which is the recommended alternative.

The alternatives are sx prop/styled(). Below are 2 examples of them:

sx prop

<Chip
  sx={{
    '& .MuiChip-deleteIcon': {
      color: 'red',
    },
  }}
  label="Deletable"
  onDelete={() => {}}
/>

styled()

const options = {
  shouldForwardProp: (prop) => prop !== 'deleteIconColor',
};
const StyledChip = styled(
  Chip,
  options,
)(({ deleteIconColor }) => ({
  '& .MuiChip-deleteIcon': {
    color: deleteIconColor,
  },
}));
<StyledChip
  label="Deletable"
  onDelete={() => {}}
  deleteIconColor="orange"
/>

Codesandbox Demo

Related