To create a custom chip component with controlled styling, you can use the makeStyles
function to define your styles. This allows you to pass variables as props to customize the appearance of the chip.
Below is an example implementation of a CustomChip component:
import React from "react";
import Chip from "@material-ui/core/Chip";
import { makeStyles } from "@material-ui/core/styles";
import { emphasize } from "@material-ui/core/styles/colorManipulator";
const useChipStyles = makeStyles({
chip: {
color: ({ color }) => color,
backgroundColor: ({ backgroundColor }) => backgroundColor,
"&:hover, &:focus": {
backgroundColor: ({ hoverBackgroundColor, backgroundColor }) =>
hoverBackgroundColor
? hoverBackgroundColor
: emphasize(backgroundColor, 0.08)
},
"&:active": {
backgroundColor: ({ hoverBackgroundColor, backgroundColor }) =>
emphasize(
hoverBackgroundColor ? hoverBackgroundColor : backgroundColor,
0.12
)
}
}
});
const CustomChip = ({
color,
backgroundColor,
hoverBackgroundColor,
...rest
}) => {
const classes = useChipStyles({
color,
backgroundColor,
hoverBackgroundColor
});
return <Chip className={classes.chip} {...rest} />;
};
export default CustomChip;
The styling logic in this component, including the use of the emphasize
function for hover and active colors, is inspired by the internal implementation of Material-UI's Chip
.
You can use the CustomChip component like this:
<CustomChip
label="Custom Chip 1"
color="green"
backgroundColor="#ccf"
onClick={() => {
console.log("clicked 1");
}}
/>
<CustomChip
label="Custom Chip 2"
color="#f0f"
backgroundColor="#fcc"
hoverBackgroundColor="#afa"
onClick={() => {
console.log("clicked 2");
}}
/>
Check out this CodeSandbox demo for a live example:
https://codesandbox.io/s/chip-color-forked-tb0vc?fontsize=14&hidenavigation=1&theme=dark
For a Material-UI v5 version, here is how you can define the CustomChip component:
import Chip from "@material-ui/core/Chip";
import { styled } from "@material-ui/core/styles";
import { emphasize } from "@material-ui/core/styles";
import { shouldForwardProp } from "@material-ui/system";
function customShouldForwardProp(prop) {
return (
prop !== "color" &&
prop !== "backgroundColor" &&
prop !== "hoverBackgroundColor" &&
shouldForwardProp(prop)
);
}
const CustomChip = styled(Chip, { shouldForwardProp: customShouldForwardProp })(
({ color, backgroundColor, hoverBackgroundColor }) => ({
color: color,
backgroundColor: backgroundColor,
"&:hover, &:focus": {
backgroundColor: hoverBackgroundColor
? hoverBackgroundColor
: emphasize(backgroundColor, 0.08)
},
"&:active": {
backgroundColor: emphasize(
hoverBackgroundColor ? hoverBackgroundColor : backgroundColor,
0.12
)
}
})
);
export default CustomChip;
Here is a CodeSandbox link to see the Material-UI v5 CustomChip in action:
https://codesandbox.io/s/chip-color-0fyh2?fontsize=14&hidenavigation=1&theme=dark