I'm trying to change the color of a material icon inside IconButton
material component (an action that should trigger color change - hover over IconButton
).
How this could be done? Adding class to the icon directly works only if hover over icon itself and not over IconButton
.
My code:
<IconButton className="add-icon-btn" onClick={toggleNominationForm}>
{!showForm ? <AddBoxIcon /> : <IndeterminateCheckBoxIcon /> }
</IconButton>
I'm trying to change the color of a material icon inside IconButton
material component (an action that should trigger color change - hover over IconButton
).
How this could be done? Adding class to the icon directly works only if hover over icon itself and not over IconButton
.
My code:
<IconButton className="add-icon-btn" onClick={toggleNominationForm}>
{!showForm ? <AddBoxIcon /> : <IndeterminateCheckBoxIcon /> }
</IconButton>
Share
Improve this question
asked Jun 16, 2020 at 15:45
KarenKaren
1,4295 gold badges26 silver badges50 bronze badges
3
|
4 Answers
Reset to default 10Here you have a full example, I hope this solves your problem:
import React from 'react'
import { makeStyles } from '@material-ui/styles'
import IconButton from '@material-ui/core/IconButton'
import AddBoxIcon from '@material-ui/icons/AddBox'
import IndeterminateCheckBoxIcon from '@material-ui/icons/IndeterminateCheckBox'
export default () => {
const [showForm, setShowForm] = React.useState(false)
const classes = useClasses()
return (
<IconButton
classes={{
root: classes.iconContainer
}}
>
{!showForm
? <AddBoxIcon className={classes.icon}/>
: <IndeterminateCheckBoxIcon className={classes.icon}/>
}
</IconButton>
)
}
const useClasses = makeStyles(theme => ({
iconContainer: {
"&:hover $icon": {
color: 'red',
}
},
icon: {
color: 'blue',
},
}))
You can use following property
sx={{ "&:hover": { color: "blue" } }}
<IconButton
size="large"
aria-label="show 17 new notifications"
color="inherit"
sx={{ "&:hover": { color: "blue" } }}
>
<Badge badgeContent={17} color="primary">
<LayersIcon />
</Badge>
</IconButton>
You need a hover
state probably. So, you can use onMouseEnter
and onMouseLeave
for the outer icon and then set the style by using this condition for the inner icon. This logic is borrowed from this answer. So, I'm setting my answer as CW.
<IconButton
onMouseEnter={() => {
setHover(true);
}}
onMouseLeave={() => {
setHover(false);
}}
className="add-icon-btn"
onClick={toggleNominationForm}
>
{!showForm ? (
<AddBoxIcon style={{ backgroundColor: hover ? "blue" : "yellow" }} />
) : (
<IndeterminateCheckBoxIcon />
)}
</IconButton>
Try adding the following CSS -
.IconButton:hover .Iconclass {
background-color: /*desired color*/;
}
<AddBoxIcon style={{backgroundColor: hover ? "blue" : "yellow"}} />
– devserkan Commented Jun 16, 2020 at 16:06