Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change Material-UI outlined Chip focus and hover color

Trying to add styles to a Material-UI chip (outlined variant) upon hovering, but not getting the expected results.

The border color is white, but the background color doesn't change at all.

So I'm questioning whether backgroundColor is even the right property anymore, but what else can it be?

const CustomChip = withStyles(theme => ({
  root: {
    "&:hover": {
      borderColor: "white",
      backgroundColor: "green"
    }
  }
}))(Chip);
like image 510
jenny Avatar asked Mar 03 '23 04:03

jenny


1 Answers

Below are the default background-color styles for the outlined variant of Chip:

    /* Styles applied to the root element if `variant="outlined"`. */
    outlined: {
      backgroundColor: 'transparent',
      '$clickable&:hover, $clickable&:focus, $deletable&:focus': {
        backgroundColor: fade(theme.palette.text.primary, theme.palette.action.hoverOpacity),
      },

In the styles above, $clickable& will be resolved to .MuiChip-clickable.MuiChip-outlined. The important aspect being that this rule is specified using two class names in addition to the pseudo-class (:hover or :focus). This means that these default styles will have greater specificity than the style rule you used for your override (which only uses one class name plus the pseudo-class). In order for your override to be successful, it needs to have specificity equal to or greater than the default styles.

One simple way to do this is to double the &. This causes the generated class name (which the ampersand refers to) to be specified twice in the rule -- increasing its specificity to match the default styles.

Here's a working example:

import React from "react";
import { makeStyles, withStyles } from "@material-ui/core/styles";
import Avatar from "@material-ui/core/Avatar";
import Chip from "@material-ui/core/Chip";

const useStyles = makeStyles((theme) => ({
  root: {
    display: "flex",
    justifyContent: "center",
    flexWrap: "wrap",
    "& > *": {
      margin: theme.spacing(0.5)
    }
  }
}));

const StyledChip = withStyles({
  root: {
    "&&:hover": {
      backgroundColor: "purple"
    },
    "&&:focus": {
      backgroundColor: "green"
    }
  }
})(Chip);
export default function SmallChips() {
  const classes = useStyles();

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

  return (
    <div className={classes.root}>
      <StyledChip variant="outlined" size="small" label="Basic" />
      <StyledChip
        size="small"
        variant="outlined"
        avatar={<Avatar>M</Avatar>}
        label="Clickable"
        onClick={handleClick}
      />
    </div>
  );
}

Edit Override outlined Chip background

like image 126
Ryan Cogswell Avatar answered Mar 05 '23 18:03

Ryan Cogswell