Ways to alter the color of an icon when hovering over it

Is there a way to change the color of a material icon inside an IconButton material component when hovering over the IconButton? I've tried adding a class directly to the icon, but it only works when hovering over the icon itself and not the IconButton.

Here's my code snippet:

<IconButton className="add-icon-btn" onClick={toggleNominationForm}>
  {!showForm ? <AddBoxIcon /> : <IndeterminateCheckBoxIcon /> }
</IconButton>

https://i.sstatic.net/5bg3x.png

Answer №1

Behold, a comprehensive example is presented below in the hopes that it will effectively address your issue:

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',
    },
}))

Answer №2

You have the option to utilize the following attribute

sx={{ "&:hover": { color: "blue" } }}
<IconButton
              size="large"
              aria-label="display 17 new notifications"
              color="inherit"
              sx={{ "&:hover": { color: "blue" } }}
            >
              <Badge badgeContent={17} color="primary">
                <LayersIcon />
              </Badge>
            </IconButton>

Answer №3

To create a hover effect, you may consider implementing a hover state using the onMouseEnter and onMouseLeave events for the outer icon. Then, based on this condition, style the inner icon accordingly. This approach is inspired by a response found in this thread. Therefore, I am marking my solution as CW.

<IconButton
  onMouseEnter={() => {
    setHover(true);
  }}
  onMouseLeave={() => {
    setHover(false);
  }}
  className="add-icon-btn"
  onClick={toggleNominationForm}
>
  {!showForm ? (
    <AddBoxIcon style={{ backgroundColor: hover ? "blue" : "yellow" }} />
  ) : (
    <IndeterminateCheckBoxIcon />
  )}
</IconButton>

Answer №4

To enhance your design, consider including the following CSS rule:

.IconButton:hover .Iconclass {
  background-color: /*chosen color*/;
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Passing a PHP variable through a URL using the GET method

I need to pass a value using the get method. The code snippet is as follows: <td><a href="cart-remove.php?id={$row['id']}" class="remove_item_link"> Remove</a></td> The value I want to send is stored in $row['id&a ...

JavaScript code to copy a specified column through the last column, and then paste it down to the last row

I have limited experience with JavaScript and I've been putting together the code I need by searching online resources and watching videos. My goal is to set multiple columns in row 4, starting from column 18 to the last column, as the active cells fo ...

What is the best way to add a "load more" button in a React application?

After writing this code, I am receiving a list of 12 objects that are being mapped. class PokemonList extends React.Component{ constructor(props){ super(props); this.state = { pokemonList: [], apiTemplateUrl: "h ...

Comparison of Uint8Array and Uint8ClampedArray

Can you explain the distinction between Uint8Array and Uint8ClampedArray within JavaScript? I've heard that Uint8ClampedArray is specifically utilized for pixel manipulations on canvas. Could you elaborate on why this array type is recommended for suc ...

Troubleshooting issue: Click function not responding inside Bootstrap modal

Below is the JavaScript code for my click function $(".addPizza").on("click", function(event) { event.preventDefault(); console.log("hello") let userId = $("#userId").attr("data-id"); let pizzaRecipe = $('#pizza-recipe').val().trim(); ...

Patience is key when waiting for Ajax response data in Vue.js

Within my Vue component, I am attempting to retrieve data from an API using axios. <template> <div> This is Default child component {{tools[0].name}} </div> </template> <script> import { CustomJS } fr ...

Directing users to a specific section on another webpage can be accomplished using HTML, JavaScript, or

<nav> <div class='container-fluid'> <h1 class='logo'>Logo</h1> <ul class='list-unstyled naving'> <li><a href='index.html'>Home</a></li> ...

Using vanilla JavaScript in a node.js environment alongside Functional Reactive Programming (FRP) with bacon.js

I am interested in incorporating Functional Reactive Programming (FRP) into my project. I have come across a popular library for node.js called bacon.js that implements FRP. However, I am having trouble finding examples of how to use bacon.js in native J ...

Child component in Angular2 makes an observer call to its parent object

Let me try to explain this in the best way possible. I have a service that includes an observable class responsible for updating itself. This observable class needs to be pushed out to the app using the observer within the service. How can I trigger that ...

Switch up the text within the URL of the background image

Simply put, this is the structure I have: <div id="RelatedPosts1"> <div class="related-posts-thumb" style="background: url(http://xxxxxxx/s72-c/image-1.jpg)"></div> <div class="related-posts-thumb" style="background: url(http: ...

The value of Yargs.argv is consistently displayed as [object Object]

In my Ubuntu 16.04 environment, I enrolled in a node.js course on Udemy. Following the instructor's guidance, I initially used the exact version mentioned and later updated to the latest version (11.0.0). Surprisingly, both versions yielded the same o ...

Steps for transforming an array into a complex array

Here is an array I have: [2, 1, 2, 1, 1, 1, 1, 1] I am looking for a way to create new arrays within the original array when the sum of values exceeds four. The desired result should look like this: [[2,1],[2,1,1],[1,1,1]] ...

Using the on-change event with a textfield can help ensure that the field is cleared if the min-date condition is not met

I recently encountered an issue with an input field that had the type "datetime" and a min-date condition set to today's date. The flow was such that if a valid date was entered, the submit button would be enabled, otherwise it would remain disabled. ...

Experiencing a 400 error while transitioning from ajax to $http?

I am facing an issue while trying to make a GET request using $http instead of ajax. The call functions perfectly with ajax, but when attempting the same with $http, I encounter a 400 (Bad Request) error. I have referenced the Angular documentation and bel ...

.displaying a grid of div elements is not functioning as expected

On a single page, there is a grid of Divs (2 by 3) with a menu (<li> in <lu>) positioned to the left of the grid. Each menu section contains its own grid of divs, all enclosed within one main div to facilitate manipulation. Menu Sections: < ...

Experiencing issues with applying bootstrap style to pagination when using react-js-pagination

I am currently utilizing the react-js-pagination library to showcase page numbers within my application. Bootstrap has been included in the public/index.html file and can be accessed using className in other components. When it comes to the Pagination com ...

Is it possible to change a react-query query dynamically on the fly?

I am working on a next.js project that involves react-query. My goal is to showcase all the countries from the API on the homepage, along with functionalities to search by name and region using an input field and select dropdown. How can I dynamically chan ...

How do I fix the build error that says "Operator '+' cannot be used with types 'number[]'?

The function below is designed to generate unique uuidv4 strings. function uuidv4() { return ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c => ( c ^ (crypto.getRandomValues(new Uint8Array(1))[0] & (15 >> (c / 4)) ...

Is there a way to identify the top five elements that are most frequently occurring in the array?

I've successfully found the element that appears the most in an array, but now I'm facing a new challenge where I need to identify the top 5 elements that appear most frequently. Here is the array: [ "fuji", "acros", &q ...

Can you provide me with some insight on the process of iterating through an object utilizing the

I've developed an app that randomly plays a sound from a selected array when a button is pressed. Now, I want to add the functionality to display and play all sounds in the array upon request. I've explored various methods such as for loops and ...