2
votes

I am trying to set a new palette theme for my react app using material-ui's createMuiTheme. This is my code for my custom theme:

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

const customTheme = createMuiTheme({
  palette: {
    primary: {
      main: '#1977d2', //blue
      contrastText: 'white',
    },
    secondary: {
      main: '#FF6600', //orange
      contrastText: 'white',
    },
    regular: {
      main: '#73C2FB' //maya
    }
  }
})

export default customTheme;

This is the code where I set the custom theme as the app's theme:

import './App.css';
import {ThemeProvider} from '@material-ui/core/styles';

import customTheme from './themes/customTheme';
import App from './app/App';

function Main() {
  return (
    <ThemeProvider theme={customTheme}>
      <App />
    </ThemeProvider>
  );
}

export default Main;

And this is the code where I try to use color regular in a component:

BarButton = ({label, callBack}) => {
    return (
      <Button variant="contained" color="regular" className={this.props.classes.appBarButton} onClick={callBack}>{label}</Button>
    )
  }

When I use color="primary" or color="secondary", it works, but color="regular" returns a default light gray color, instead of #73C2FB, that is a light blue.

I followed these directions to achieve what I am aiming, but it is not working.

1
Button only supports primary and secondary theme colors. Various MUI components support different palette properties as string values for the color prop, but never custom ones. You need to apply this as theme.palette.regular.main via the style or className prop.hotpink
@hotpink thanks man, it worked. You should post it as an answer so everybody else with the same doubt get it solved. And you collect some points also.HuLu ViCa

1 Answers

2
votes

Custom theme properties can never be applied to any MUI component via the color prop. The reason for this is that MUI takes the the interpolated string value to apply styling via its default props. Your example of

<Button variant="contained" color="regular">{label}</Button>

would look for a containedRegular property of classes that does not exist. IIUC MUI should also provide a props validation error.

Instead, custom theme colors can be applied via the styles or className props.

const useStyles = makeStyles(theme => ({
  regular: {
    color: theme.palette.regular.main
  }
}))

const classes = useStyles()
const theme = useTheme()

<Button style={{color: theme.palette.regular.main}}>foo</Button>
<Button className={classes.regular}>bar</Button>