Home > Enterprise >  Use custom color schema in mui theme
Use custom color schema in mui theme

Time:10-11

I would like to configure some colors in my theme, which are used by some categories in my application.

So I've setup a theme and use this in my component.

theme.tsx

import { createTheme, Theme } from '@mui/material/styles'
import { red } from '@mui/material/colors'

export const theme: Theme = createTheme({
  palette: {
    primary: {
      main: blue[800]
    },
    secondary: {
      main: '#19857b'
    },
    cat1: {
      main: red[700]
    }
  }
})

circle.tsx

import CircleIcon from '@mui/icons-material/FiberManualRecord'
import {theme} from '/shared/theme'

export function Circle() {
  return (
    <>
    <CircleIcon style={{ color: theme.palette.cat1.main }} />
    <CircleIcon style={{ color: theme.palette.cat1[200] }} />
    </>
  )
}

What I try to achieve is to set the color of some elements in a dynamic way. So the Circle in category 1 will get the color red. All colors which are needed are imported in the theme. I don't want to import all possible colors in the component itself.

But I also want to calculate the color of another element based on this. In the example above I would like to get 200 of red.

CodePudding user response:

First off, don't use styles, it's harder to override and MUI has better alternatives (sx prop/styled function) which provide the theme object for you when passing as a callback, so change your code to:

<CircleIcon sx={{ color: theme => theme.palette.cat1.main }} />

Secondly, if you want to access other variants of the color like what you can with primary or secondary, use augmentColor() function to tell MUI generate the dark/light/contrastText colors automatically for you:

import {
  createTheme,
  ThemeProvider,
  Theme,
  lighten,
  darken
} from "@mui/material/styles";

const { palette } = createTheme();
const { augmentColor } = palette;
createTheme({
  palette: {
    // this will tell MUI to calculate the main, dark, light and contrastText
    // variants based on the red[500], and then merge the new properties with
    // the color object itself. The end result will be something like:
    // cat1: { '100': ..., '900': ..., light: ..., dark: ..., contrastText: ... }
    cat1: augmentColor({ color: red }),

    // this will tell MUI to calculate the main, dark, light and contrastText
    // variants based on the red[100], no other shades are passed unlike the above.
    cat2: augmentColor({ color: { main: red[100] } })

    // light and dark variants are generated in augmentColor using lighten() and
    // darken() function, if you want even more control, override the light and
    // dark properties yourself like this:
    cat3: augmentColor({
      color: {
        dark: darken(red[300], 0.6),
        main: red[300],
        light: lighten(red[300], 0.6)
      }
    })
  }
})

Live Demo

Codesandbox Demo

  • Related