Is there a way to customize the checkbox styles and icons in Material-UI React when hovering over them?

Incorporating material-ui into my current project, I've customized a Checkbox to display in red color.

My goal is to have the checked Icon appear only when a user hovers over the Checkbox. However, it should remain hidden when not hovered. Unfortunately, I'm struggling to identify the correct selector to achieve this effect. Any suggestions on how to accomplish this would be greatly appreciated.

Answer №1

https://i.sstatic.net/QTGmS.gif

Here are some key points to consider:

  • Utilize Material-UI's nesting selector to target the SVG element within the <Checkbox />, as it is a library element with a static DOM structure.

  • Employ &:hover to capture the onMouseOver event.

  • Use d: path(value) to pass the value of prop d to the child element <path /> within the SVG.

import React from "react";
import "./styles.css";
import { Checkbox } from "@material-ui/core";
import { makeStyles } from "@material-ui/core/styles";
import AcUnit from "@material-ui/icons/AcUnit";

const useStyles = makeStyles(theme => ({
  root: {
    background: "#f1f1f1",
    "&:hover": {
      "& span": {
        "& svg": {
          "& path": {
            d:
              "path('M12 2c1.1 0 2 .9 2 2s-.9 2-2 2-2-.9-2-2 .9-2 2-2zm9 7h-6v13h-2v-6h-2v6H9V9H3V7h18v2z')"
          }
        }
      }
    }
  }
}));

export default function App() {
  const classes = useStyles();
  return (
    <div className="App">
      <Checkbox className={classes.root} icon={<AcUnit />} />
    </div>
  );
}

Test it out online:

https://codesandbox.io/s/amazing-golick-rjmcs?fontsize=14&hidenavigation=1&theme=dark


Reference: the structure of <Checkbox /> as seen in the browser

<span
  class="MuiButtonBase-root MuiIconButton-root PrivateSwitchBase-root-8 MuiCheckbox-root MuiCheckbox-colorSecondary makeStyles-root-85 MuiIconButton-colorSecondary"
  aria-disabled="false"
>
  <span class="MuiIconButton-label">
    <input
      class="PrivateSwitchBase-input-11"
      type="checkbox"
      data-indeterminate="false"
      value=""
    /><svg
      class="MuiSvgIcon-root"
      focusable="false"
      viewBox="0 0 24 24"
      aria-hidden="true"
      role="presentation"
    >
      <path
        d="M22 11h-4.17l3.24-3.24-1.41-1.42L15 11h-2V9l4.66-4.66-1.42-1.41L13 6.17V2h-2v4.17L7.76 2.93 6.34 4.34 11 9v2H9L4.34 6.34 2.93 7.76 6.17 11H2v2h4.17l-3.24 3.24 1.41 1.42L9 13h2v2l-4.66 4.66 1.42 1.41L11 17.83V22h2v-4.17l3.24 3.24 1.42-1.41L13 15v-2h2l4.66 4.66 1.41-1.42L17.83 13H22z"
      ></path>
    </svg>
  </span>
  <span class="MuiTouchRipple-root"></span>
</span>

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

Error: Unable to access attributes of an undefined object (looking for 'item')

Every time I attempt to execute the following code, I encounter this error. import React from 'react' import { Accordion} from 'react-bootstrap/Accordion'; import { ToastContainer } from 'react-toastify'; const myaccordion = ( ...

Encountered an Error: The JSON response body is malformed in a NextJS application using the fetch

Running my NextJS app locally along with a Flask api, I confirmed that the Flask is returning proper json data through Postman. You can see the results from the get request below: { "results": [ [ { "d ...

An issue has been identified where the Export to Excel and PDF functionality is not functioning properly within a Datatable after applying a

I am using multiple select option filtering with ajax, jQuery, and PHP in a datatable. The records are being filtered correctly, but after changing the select option, the Export to Excel/ PDF functionality is not working properly. Note:- (1) It always do ...

Issue with module.exports entry in Webpack configuration causing errors

I've been working on setting up webpack but I've hit a roadblock due to this error message. It seems like there's an issue with the entry configuration. When I try to add it without specifying a path, as shown in the tutorial, I receive the ...

Is it possible to eliminate the array from a property using TypeScript?

Presenting my current model: export interface SizeAndColors { size: string; color: string; }[]; In addition to the above, I also have another model where I require the SizeAndColors interface but without an array. export interface Cart { options: ...

Saving a collection of React.js components in JavaScript to a specific location or storage for future use

Important Note: I am unable to utilize the Node FS module as my knowledge about npm and fs is limited. In my current project, I am developing a simple game where users can interact by clicking a button to display an image of a 'duck' on screen. ...

Encounter an HTTP error through Ajax triggered by an asynchronous click event using ZombieJS

I am currently working on a webpage that utilizes knockout.js and has a click handler. When the button is clicked, it triggers an AJAX request to an API server, which then responds with a contextual HTTP status result. For instance, if the user is unautho ...

Typescript and the way it handles responses from REST APIs

Starting off, I must mention that I am relatively new to TypeScript, although I have been a JavaScript developer for quite some time. I am in the process of transitioning my existing JavaScript application to TypeScript. In the current JavaScript app, the ...

Creating a custom dialog box using JavaScript

How can I create a customized dialog box in the center without displaying "the host name says..." using CSS? function myFunction() { alert("Record Save"); } Thank you in advance! ...

What is the best way to serve individual static files in Express without revealing the entire "/static" directory?

For my new project, I am working on a simple setup that involves using JWT for authorization. The project is being served entirely through express, with no separation between frontend and backend. My goal is to dynamically serve specific HTML files based o ...

How can I ensure my function waits for a promise to be resolved using Async / Await?

I'm running into an issue where I want my function to keep executing until the nextPageToken is null. The problem occurs when the function runs for the first time, it waits for the promise to resolve. However, if there is a nextPageToken present in th ...

ways to view a user's profile through a search query or by clicking on their profile link

Here, I have created a hyperlink to the customer. <a name="id" href="https://127.0.0.1/newtaxicab/account/driver/profile/index.php?id=<?php echo $data['id']; ?>"><?php echo $data['fullname']; ?></a> The content ...

Switching from ejs format to html

I've been working on a tutorial that uses ejs, but I'm not too familiar with it. I'd like to know how to convert the server.js from using ejs to html. Here's the code snippet: app.set('view-engine', 'ejs') app.use( ...

Using the Jquery setTimeout function to initiate a change event

In my system, each question has a time limit of 10 seconds. If a student does not answer within that time, the question will automatically move to the next one. However, if the student does mark an answer, they will be taken immediately to the next questio ...

Excluding the decimal point from version 1.0 in an API response with Angular 5

When working with Angular 5, I encountered an issue where the API response was returned as 1.0, but when displayed in the HTML field it only showed as 1. Upon inspecting the response in Chrome dev-tools, under the Network tab -> Response, it correctly ...

Are XHR2 credential requests truly secure or easily faked?

I am working to determine the level of security provided by credentialed XHR2 requests. More precisely, can I verify that the request originated from a browser runtime environment, and not from a bot (such as a server-side program) that might be able to m ...

Trouble with displaying image sources in dynamic content with Vue and Vuetify

Currently, I am developing a component that displays tabs along with their corresponding HTML content using v-tab, v-tab-items, and v-tab-item. In the v-tab-item section, I have included the following snippet: <v-card flat> <v-card-text v-html=& ...

Expanding a website banner slide to fill the entire width of the page

Is there a way to ensure that the banner images in the website below flow seamlessly? Currently, it seems like the current image is cut off on the left and part of the previous image shows up in its place. I'd like the current image to occupy the ent ...

I am facing a challenge with AngularJS where I am unable to navigate between pages using the

I'm having issues with my route file app.js. Whenever I click on any link or button, it redirects me to books.html. What could be the mistake I'm making? var myApp = angular.module('myApp', ['ngRoute']); myApp.config([&apo ...

How to ensure scrollbar adjusts to increasing height when using scroll:auto?

My <div> element has the style property scroll:auto. Whenever text is added to the <div> and the content height exceeds the default height, I find myself having to scroll down in order to see the latest lines of text that have been added. What ...