Search code examples
reactjscolorsmaterial-uithemes

Material UI Adding Custom Color in Theme Not Recognized


I am trying to create a custom theme with custom colors using Material UI in React. When I create the custom theme and view it in the console, I can see the new color with its value. But when I try to reference it in a component, in my case a Switch, I get the following error

index.js:1 Warning: Failed prop type: Invalid prop color of value neutral supplied to ForwardRef(Switch), expected one of ["default","primary","secondary"]

When I set the color to "primary" or "secondary", I get the expected color. It just seems to not allow for the new color I created.

Here is my theme:

import { createMuiTheme } from "@material-ui/core/styles";

const customTheme = createMuiTheme({
    palette: {
        primary: {
            main: "#33d9b2"
        },
        secondary: {
            main: "#40407a"
        },
        neutral: {
            main: "#ff793f"
        }
    }
});

export default customTheme;

Here is my Switch component:

<FormGroup>
   <FormControlLabel
        control={<Switch color="neutral" checked={this.props.isChecked} onChange={this.handleToggleChecked} />}
        label="2018 Tracks">
   </FormControlLabel>
</FormGroup>

Solution

  • Ciao, according to Material UI Switch docs, color prop accepts only default, primary or secondary values.

    If you want to make a switch with your neutral color, you have to make a custom switch. Something like:

    import { withStyles } from '@material-ui/core/styles';
    ...
    const NeutralSwitch = withStyles({
        switchBase: {
            color: "#808080",  //grey if unchecked
            '&$checked': {
                color: "#ff793f",   //neutral color
            },
            '&$checked + $track': {
                backgroundColor: "#ff793f",   //neutral color
            },
        },
        checked: {},
        track: {},
    })(Switch);