cssreactjsmaterial-uijss

Access Button Primary Color In React


I am trying to provide overrides in the theme for buttons that are contained, primary and hovered. I tried this but it doesn't work

CODESANDBOX LINK CLICK HERE

theme/overrides/MuiButton.js

import palette from '../palette';

export default {
  contained: {
    backgroundColor: '#FFFFFF',
    '&.primary': {
      '&:hover': {
        backgroundColor: palette.primary.dark,
      },
    },
  },
};

theme/overrides/index.js

import MuiButton from "./MuiButton";

export default {
  MuiButton
};

theme/index.js

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

import palette from "./palette";
import typography from "./typography";
import overrides from "./overrides";

const theme = createMuiTheme({
  palette,
  typography,
  overrides,
  zIndex: {
    appBar: 1200,
    drawer: 1100
  }
});

export default theme;

Solution

  • The best resource for determining how to appropriately override the default styles in your theme, is to look at how the default styles are defined.

    From https://github.com/mui-org/material-ui/blob/v4.11.0/packages/material-ui/src/Button/Button.js#L138:

      containedPrimary: {
        color: theme.palette.primary.contrastText,
        backgroundColor: theme.palette.primary.main,
        '&:hover': {
          backgroundColor: theme.palette.primary.dark,
          // Reset on touch devices, it doesn't add specificity
          '@media (hover: none)': {
            backgroundColor: theme.palette.primary.main,
          },
        },
      },
    

    Translating this approach to the code in your question would look like this:

    import palette from '../palette';
    
    export default {
      containedPrimary: {
        backgroundColor: '#FFFFFF',
        '&:hover': {
          backgroundColor: palette.primary.dark,
        },
      },
    };
    

    Edit Material demo