How to change icon color on hover?

Viewed 9246

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>

enter image description here

4 Answers

Here 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*/;
}
Related