Luis García
Luis García

Reputation: 53

How to target input type=radio elements in CSS using Material UI inside a component?

In CSS I would use input[type="radio"]:checked { color: #000} but in Material UI that expression is not valid.

In Material UI I create rules using makeStyles:

const useStyles = makeStyles(() => ({ text: { color: "red", }, }));

How can I target input[type="radio"] elements using makeStyles?

Upvotes: 0

Views: 1077

Answers (2)

95faf8e76605e973
95faf8e76605e973

Reputation: 14191

You can use "&:checked" to target checked radio buttons. That is assuming you are using the native input DOM component. If you are using the MUI <Radio/>, you can target the rule name checked

const useStyles = makeStyles({
  customRadio: {
    "& + label" : {
      color: "green"
    },
    "&:checked + label" : {
      color: "red"
    }
  }
})

function App() {

  const classes = useStyles();

  return (
    <div>
      <div>
        <input className={classes.customRadio} type="radio" id="foo" name="test" value="foo" defaultChecked={true} />
        <label htmlFor="foo">foo</label>
      </div>
      <div>
        <input className={classes.customRadio} type="radio" id="bar" name="test" value="bar" />
        <label htmlFor="bar">bar</label>
      </div>
    </div>
  );
}

ReactDOM.render(<App/>, document.getElementById("root"));
<body>
  <div id="root"></div>

  <script src="https://unpkg.com/react@16/umd/react.development.js"></script>
  <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
  <script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
  <script src="https://unpkg.com/@material-ui/core@latest/umd/material-ui.development.js"></script>

  <script type="text/babel">
    const { makeStyles } = MaterialUI;
  </script>
</body>

Upvotes: 1

Antonio Erdeljac
Antonio Erdeljac

Reputation: 3244

Have you tried something like this?

const useStyles = makeStyles(() => ({ text: { color: "red", }, 'input[type="radio"]:checked': { color: '#000' } }));

Upvotes: 0

Related Questions