reactjsmaterial-uicss-in-js

Material UI Overriding styles with increased specificity


How can I override a rule of a class which has high specificity?

For example, the .MuiAccordionSummary-content.Mui-expanded class in the AccordionSummary

const useStyles = makeStyles(() => ({
    expanded: {
        marginBottom: 0,
    },
}));

in combination with:

<AccordionSummary classes={{
    expanded: classes.expanded,
}}/>

is applied but overridden.

Note: marginBottom: '0 !important' works, but doesn't feel like an optimal solution.


Solution

  • You could use global overrides to change the default margin of the AccordionSummary. However, this will affect all AccordionSummary components in your application.

    The better approach (the one you are already using) is to wrap the component and alter its classes. If you look into the source of the AccordionSummary, you will find that the expanded property is an empty block. The margin gets set by the referencing selector in the content property:

        content: {
          display: 'flex',
          flexGrow: 1,
          transition: theme.transitions.create(['margin'], transition),
          margin: '12px 0',
          '&$expanded': {
            margin: '20px 0',
          },
        },
    

    If you add the same reference in your custom styles, the priority becomes higher and you won't need !important. You will have to add the expanded className to your custom styles though:

    import React from 'react';
    import makeStyles from '@material-ui/core/styles/makeStyles'
    import Accordion from '@material-ui/core/Accordion';
    import AccordionDetails from '@material-ui/core/AccordionDetails';
    import AccordionSummary from '@material-ui/core/AccordionSummary';
    
    const useStyles = makeStyles(() => ({
      expanded: {},
      content: {
        '&$expanded': {
          marginBottom: 0,
        },
      },
    }));
    
    const MyAccordion = ({ summary, details }) => {
      const classes = useStyles();
    
      return (
        <Accordion>
          <AccordionSummary classes={{ content: classes.content, expanded: classes.expanded }}>
            {summary}
          </AccordionSummary>
          <AccordionDetails>
            {details}
          </AccordionDetails>
        </Accordion>
      )
    };
    
    export default MyAccordion;