Override delete icon margin styles in MUI Chip component

Viewed 75

I'm using V4 MUI Chip component with size : 'small' and variant: 'outlined' with a deleteIcon specified.

https://v4.mui.com/components/chips/

I'd like to override the margin-right property of the deleteIcon but I'm having trouble getting the right specificity, because MUI is applying more specific styles.

The following styles are applied to the delete icon by MUI:

.MuiChip-outlined-253 .MuiChip-deleteIconSmall-267 {
    margin-right: 3px;
}
.MuiChip-outlined-253 .MuiChip-deleteIcon-266 {
    margin-right: 5px;
}

How do I apply a style to override the margin-right of the deleteIcon and set it to e.g. '10px'?

1 Answers

You can use the class .MuiChip-deleteIcon based on the Chip api documentation (https://v4.mui.com/api/chip/)

Here is a working codesandbox to play with (has for the both default and outlined variants).

Here is the code to implement the change you want.

import React from "react";
import { makeStyles } from "@material-ui/core/styles";
import Chip from "@material-ui/core/Chip";
import FaceIcon from "@material-ui/icons/Face";

const useStyles = makeStyles((theme) => ({
  root: {
    display: "flex",
    justifyContent: "center",
    flexWrap: "wrap",
    "& > *": {
      margin: theme.spacing(0.5)
    },
    //Here is where you customise the css for the delete icon
    "& .MuiChip-deleteIcon": {
      marginRight: "20px", // Change those values to yours
    },
    //For customising the outlined the css for the delete icon 
    "& .MuiChip-outlined": {
      "& .MuiChip-deleteIcon": {
        marginRight: "10px", // Change those values to yours
      }
    }
  }
}));

export default function Chips() {
  const classes = useStyles();

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

  const handleClick = () => {
    console.info("You clicked the Chip.");
  };

  return (
    <div className={classes.root}>
      <Chip label="Deletable primary" onDelete={handleDelete} color="primary" />
      <Chip
        icon={<FaceIcon />}
        label="Deletable secondary"
        onDelete={handleDelete}
        color="secondary"
      />
      <Chip
        icon={<FaceIcon />}
        label="Deletable secondary"
        onDelete={handleDelete}
        color="secondary"
        variant="outlined"
      />
    </div>
  );
}

Another way would be to do something similar in the theme.

Related