Search code examples
reactjsmaterial-uistyled-components

Apply radiobutton color using styled-components in Material UI?


In the Material UI documents, they provided sample code to show how one can change the color of a Radiobutton.

const GreenRadio = withStyles({
  root: {
    color: green[400],
    '&$checked': {
      color: green[600],
    },
  },
  checked: {},
})(props => <Radio color="default" {...props} />);

I would like to replicate this with styled-component instead i.e. const StyledRadio = styled(Radio) but I am not too familiar with the syntax such as the ampersand and the dollar sign - how can I do this?


Solution

  • When using styled components with MUI, the CSS is applied to the root class of the component. If you need to apply a more specific style, then you'll need to target the relevant class. In this case, you'll need to target the .Mui-checked class:

    const StyledRadio = styled(Radio)`
      color: ${green[400]};
      &.Mui-checked {
        color: ${green[600]};
      }
    `;
    

    The MUI docs are really good in that they list the CSS classnames for each component. If you visit the API docs for the Radio component, you'll see the .Mui-checked class listed there (under the 'Global Styles' column).

    Here's a working example in Code Sandbox: https://codesandbox.io/embed/styled-components-9pewl