HuLu ViCa
HuLu ViCa

Reputation: 5456

Set new color for material-ui theme

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.

Upvotes: 4

Views: 3141

Answers (1)

hotpink
hotpink

Reputation: 3226

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>

Upvotes: 4

Related Questions