0
votes

I'm new to material UI. While learning, I came to know out that styles of a material UI can be overridden with the rule name of the classes.

If I have an element - MenuItem where I just need to change the default styling of the text (such as fontFamily, fontWeight, fontSize)

According to the documentation available here https://material-ui.com/api/menu-item/ I used makeStyles hook and have overridden some properties of the root element of Menu-Item

Sample code

const useStyles = makeStyles((theme) => ({
  menuItem: {
            fontFamily: "Raleway",
      }
  }));

JSX code: <MenuItem onClick={handleClose} component={Link} to="/services" classes={{root: classes.menuItem}}>Services</MenuItem>

In one more tutorial, I found another way of overriding - with className like

const useStyles = makeStyles((theme) => ({
      menuItem: {
                fontFamily: "Raleway",
          }
      }));
    
    JSX code: <MenuItem onClick={handleClose} component={Link} to="/services" className={classes.menuItem}>Services</MenuItem>

My question lies in this part className={classes.menuItem} and classes={{root: classes.menuItem}}

On using root -> I see the css properties getting added to the root element but on using className={classes.menuItem} I see a new class is added to the DOM. But Is there any difference with respect to the behaviour of the app between these 2 methods or is it just another way of doing it?

Thanks

1

1 Answers

1
votes

From what I can tell having worked with Material UI, the difference is with what you're trying to do.

className={classes.menuItem} and classes={{root: classes.menuItem}} will both get you the results that you're expecting, as you've already discovered.

The distinctions are important when you start building custom themes, because Material UI allows you to apply classes to the components as a whole, meaning potentially comprised of other components, or pass along styles to the root elements if you need a higher specificity.

For example, consider the Stepper component.

classes={{root: classes.menuItem}} will override the root in the component, applying your styles.

className={classes.menuItem} will add an additional class to the component, leaving the underlying styles intact.