Material-ui [Chip] On hover show delete icon

I have been trying to get the on-hover property of the chip. The desired response should be like, when I hover on a chip from a chip array, it should show the delete icon.

I have attached the snippet:-

  chip: {
    "&:hover": {
      backgroundColor: darken(
        theme.palette.primary.main,
        theme.palette.action.hoverOpacity * 3,
      ),
    },
  },
            <Chip
              className={classes.chip}
              key={i}
              label={tag.label}
              size="small"
              color={state.edit === false ? "primary"
                : tag.to_del ? "secondary"
                  : tag.is_new ? "primary"
                    : "default"}
              onDelete={state.edit === true ? ((e) => state.deleteTag(i)) : undefined}
              // onMouseEnter={}
              onMouseDown={(e) => e.preventDefault()}
            />

Answer

You are almost there, you are only missing the mouse enter and leave bindings to handle your delete logic:

  const [state, setState] = useState({ edit: false});
  const handleMouseEnter = () => setState(state=>({...state, edit: true }));
  const handleMouseLeave = () => setState(state=>({...state, edit: false }));

  <Chip
    // ...
    onMouseEnter={handleMouseEnter}
    onMouseLeave={handleMouseLeave}
  />;

I made the changes to get the behavior you are looking for (as shown above):

https://codesandbox.io/s/chips-material-demo-forked-9f1u4?file=/demo.js

Leave a Reply

Your email address will not be published. Required fields are marked *