When to use ‘classes’ vs ‘className’ with Material UI?

This is a very confusing aspect of MUI, but once you get it – it’s super easy.

Consider that YOU are writing a component, and style it using JSS:

const useStyles = makeStyles(theme => ({
  root: {
    margin: theme.spacing(1)
  },
  in: {
    padding: 8
  }
}));

function MyComponent(){
  const classes = useStyles();
  return (
    <Outside className={classes.root}>
      <Inside className={classes.in} />
    </Outside>
  )
}

Notice that the component is essentially a composition (or a hierarchy) of components – Outside and Inside in this minimal example, but MUI components often have more than two (styled) nested components.

Now you want to export this component as part of a library and allow developers to style all the components involved (both Outside and Inside). How would you do it?

What MUI does, is it allows you to provide a classes property (you’ll see in the docs each component’s rule names – root and in in our example) that will be merged into MUI’s own rules, or stylesheet if you wish (in the MUI code this is done using the withStyles HOC).

For convenience, every component also accepts className property that is merged into the className of the root element (Outside in our case).

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)