Bassem
Bassem

Reputation: 4030

How to Customize MaterialUI Color Shades

I understand that in MaterialUI, it is possible to customize the theme to use different colors.

The colors exposed by MaterialUI, have different shades. For instance:

import purple from '@material-ui/core/colors/purple';

const theme = createMuiTheme({
  palette: {
    primary: {
      main: purple,
    },
    secondary: {
      main: "#22B469",
      light: "rgb(78, 195, 135)",
      dark: "rgb(23, 125, 73)",
      contrastText: "#ffffff"
    },
  },
});

Looking at the console.log(theme), we see that the primary color is filled with shades, but not for the secondary color, where the color has been overridden by a hex color code.

console.log(theme)

In MaterialUI documentation, it's only mentioned to use light, main, dark, and contrastText when using a custom hex color.

Sure, I can add those shades one by one under the secondary key, but this solution doesn't look elegant.

What are the best practices when overriding a theme color with hex code and is there a way to auto-generate the shades from a custom hex color?

Upvotes: 0

Views: 2118

Answers (2)

JB_DELR
JB_DELR

Reputation: 777

You can make a custom color generated here in a module and import it.

const amber = {
  50: '#fff8e1',
  100: '#ffecb3',
  200: '#ffe082',
  300: '#ffd54f',
  400: '#ffca28',
  500: '#ffc107',
  600: '#ffb300',
  700: '#ffa000',
  800: '#ff8f00',
  900: '#ff6f00',
  A100: '#ffe57f',
  A200: '#ffd740',
  A400: '#ffc400',
  A700: '#ffab00'
};
const _default = amber;
exports.default = _default;

Upvotes: 2

JB_DELR
JB_DELR

Reputation: 777

import purple from '@material-ui/core/colors/purple';
import indigo from '@material-ui/core/colors/indigo';


const theme = createMuiTheme({
  palette: {
    primary: {
      main: purple,
    },
    secondary: {
      main: purple,
      light: "rgb(78, 195, 135)",
      dark: "rgb(23, 125, 73)",
      contrastText: "#ffffff",
      indigo: indigo  //<---------- do what you want
    },
  },
});

then in your style definition:

{...
root: {
   color: theme.palete.secondary.indigo[700],
},
...}

Upvotes: 0

Related Questions