I am trying change the foreground color of a material ui v4 button that has a svg image and text. The text changes color alright, however not the image. I have dropped in the browser debugger and tried setting the color css manually on the button, it doesn’t even work there, do I need to use a different attribute besides color? I have to use v4 since the rest of the code base is that.
import image from "Images/icons/icon.svg";
import clsx from "clsx";
import {Button, makeStyles, Typography} from "@material-ui/core";
const styles = makeStyles((theme) => ({
button: {
color: "black",
"&:hover": {
color: "red",
"& $icon": {
color: "red",
}
},
},
icon: () => ({
color: "black",
}),
layout: {
textTransform: 'none',
color: "inherit",
},
}));
const classes = styles(props);
return (
<>
<Button
color="inherit"
className={clsx(classes.button)}
onClick={handleClick}
startIcon={
<img className={clsx(classes.icon)} src={image} />}
>
<Typography className={clsx(classes.layout)}>
Share
</Typography>
</Button>
<>
);
If I add a second image in a different color and change the Button component to add these fields it works, however it seems like a very hacky solution, any idea how to do this in css?
<Button
color="inherit"
className={clsx(classes.shareButton)}
onClick={handleClick}
onMouseEnter={(e: any) => {
e.currentTarget.children[0].children[0].children[0].src = imageHover
}}
onMouseLeave={(e: any) => {
e.currentTarget.children[0].children[0].children[0].src = image
}}
startIcon={
<img
className={clsx(classes.icon)}
src={image}
/>}
2
Answers
Instead of using
<img>
tag, use the raw SVG instead. This allow you to specifyfill="currentColor"
property, which inherits from font color of the parent. Example below:I guess your main goal is to set
fill="currentColor"
to your svg image.Here’s an example.