Abhishek Sarkar
Abhishek Sarkar

Reputation: 498

Support for gradient directly in theme configurations in material-ui

Right now we can configure the theme in material-ui as follows.

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

const theme = createMuiTheme({
  palette: {
    primary: {
      main: '#ff4400'
    },
    secondary: {
      light: '#0066ff',
      main: '#0044ff',
      contrastText: '#ffcc00',
    },
    // error: will use the default color
  },
});

Is there a way to provide gradient configuration for primary and secondary colours? IMHO subtle gradients give better colour pops and make the flat colours slightly less boring

Upvotes: 5

Views: 13654

Answers (1)

n1stre
n1stre

Reputation: 6086

You could set gradient values inside of your theme:

const theme = createMuiTheme({
  palette: {
    primary: {
      main: '#ff4400',
      mainGradient: "linear-gradient(to right, tomato, cyan)",
    },
    // ...
  },
});

And then use this value inside of components style prop:

<AppBar
  position="static"
  style={{ background: theme.palette.primary.mainGradient }}
> ...

EDIT

This is indeed feels hacky, but i believe this is the only way at the moment. I haven't found any examples of this in the MUI docs. And if you check out the source of <AppBar /> component, you'll find out that it is impossible to use main, light or dark colors as linear-gradients:

export const styles = theme => {
  //...

  return {
    /* ... */

    /* Styles applied to the root element if `color="primary"`. */
    colorPrimary: {
      backgroundColor: theme.palette.primary.main, 
      color: theme.palette.primary.contrastText,
    },
    /* Styles applied to the root element if `color="secondary"`. */
    colorSecondary: {
      backgroundColor: theme.palette.secondary.main,
      color: theme.palette.secondary.contrastText,
    },
  };
};

As you can see backgroundColor is used here. It would be invalid to set linear-gradient(...) to it.

Upvotes: 11

Related Questions