Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access light and dark variants of React Material-UI primary and secondary colors?

The Material-UI docs for React say that light and dark variants of your primary and secondary colors will be calculated automatically.

(From the docs: https://material-ui.com/customization/palette/)

const theme = createMuiTheme({
  palette: {
    primary: {
      // light: will be calculated from palette.primary.main,
      main: '#ff4400',
      // dark: will be calculated from palette.primary.main,

What I can't seem to find is how to access these colors for use in my components. After implementing a theme like so:

const theme = createMuiTheme({
  palette: {
    secondary: {
      main: '#287a9f'
    }
  }
})

How would I then specify that I'd like a component to use the light variant of the secondary color? Something like:

<AppBar color="Primary.light" />

I could certainly just implement them manually as custom colors, but this seems to defeat the purpose of automatic calculation.

Wisdom much appreciated.

like image 849
Andrew Avatar asked Apr 02 '20 18:04

Andrew


1 Answers

When you create your custom theme pass it to ThemeProvider like this:

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

const theme = createMuiTheme({
  palette: {
    secondary: {
      main: '#287a9f'
    }
  }
});

function App() {

  return (
    <ThemeProvider theme={theme}>
      <Children />
    </ThemeProvider>
  )
}

And there are many ways to access the theme variables, for example you could use makeStyles or useTheme:

makeStyles:

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

const useStyles = makeStyles(theme => ({
 myComp: { backgroundColor: theme.palette.primary.light }
});

function DeepChild() {
  const classes = useStyles();

  return <Component className={classes.myComp} />;
}

useTheme:

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

function DeepChild() {
  const theme = useTheme();

  return <Component color={theme.palette.primary.light} />;
}

Note that the color property of the AppBar component supports one of

["default","inherit","primary","secondary","transparent"]

So in order to override the color for an AppBar component, as in your example, you need to pass a custom class:

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

const useStyles = makeStyles(theme => ({
 appBar: { backgroundColor: theme.palette.primary.light }
});

function DeepChild() {
  const classes = useStyles();

  return <AppBar className={classes.appBar} />;
}
like image 159
Fraction Avatar answered Sep 23 '22 09:09

Fraction