3

I have a check box (not a Material-UI checkbox) that I'd like to style using it's aria-checked="true" attribute via makeStyles. I see in the Material-UI docs that you can style pseudo selectors as such:

'&:hover': { /* … */ },

But I haven't been able to make this work for the aria attribute? Is this possible? If so, how?

Ryan Cogswell
  • 75,046
  • 9
  • 218
  • 198
insivika
  • 576
  • 2
  • 10
  • 21

2 Answers2

7

The syntax for attribute selectors is largely the same as in CSS. & is used to refer to the generated class (classes.myCheckboxStyles in my example below) and then further selectors can be added within the quotes (e.g. "&[aria-checked=true]").

Below is a working example demonstrating the syntax:

import React from "react";
import { makeStyles } from "@material-ui/core/styles";

const useStyles = makeStyles({
  myCheckboxStyles: {
    border: "1px black solid",
    color: "white",
    "&[aria-checked=true]": {
      backgroundColor: "blue"
    }
  }
});
export default function Checkboxes() {
  const classes = useStyles();
  const [checked, setChecked] = React.useState(false);
  return (
    <div>
      <span
        onClick={() => setChecked(!checked)}
        aria-checked={checked}
        className={classes.myCheckboxStyles}
      >
        X
      </span>
    </div>
  );
}

Edit aria-checked styling

Ryan Cogswell
  • 75,046
  • 9
  • 218
  • 198
0

I've tried to use aria-checked="true" to activate MUI checkbox, but it doesn't work. So, in my view, you should try using onMouseEnter to activate MUI checkbox. You can try this:

import React from "react";
import Checkbox from "@material-ui/core/Checkbox";

export default function Checkboxes() {
  const [checked, setChecked] = React.useState(false);

  const handleChange = event => {
    setChecked(event.target.checked);
  };

  return (
    <div>
      <Checkbox
        checked={checked}
        onMouseEnter={() => setChecked(true)}
        onChange={handleChange}
        inputProps={{ "aria-label": "primary checkbox" }}
      />
    </div>
  );
}

Edit Select with checkboxes and sub headers

Michael
  • 1,806
  • 2
  • 11
  • 20