What are themes when it comes to Material UI?

Viewed 1631

I'm trying understand what exactly themes are and what they're trying to represent. I've read the docs but it still doesn't make sense to me.

For example, below is a piece of code of what I'm referring to.

I just want to know what theme is supposed to represent, where it's coming from and why it's used.

const styles = theme => ({
root: {
    display: 'flex',
},

toolbar: {
    paddingRight: 24, // keep right padding when drawer closed
},

toolbarIcon: {
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'flex-end',
    padding: '0 8px',
    ...theme.mixins.toolbar,
},
});
2 Answers

The Material-UI documentation covers this pretty thoroughly, but there are a few different parts of the documentation necessary to understand the code you posted.

As far as why the theme is used, the documentation covers this some, but one use case is controlling color schemes. For instance, if you have a multi-tenant application (one code base used for multiple clients), you may want to support using colors that are specific to each client's branding. Themes provide a way of changing colors, fonts, and other look-and-feel aspects dynamically by simply providing a different theme at the root of your app. In the particular example you posted, the theme is being used to pull in some CSS for the look of toolbars that is included in Material-UI's default theme but which could be overridden in a custom theme.

Here is the Material-UI code that is responsible for the defaults for theme.mixins.toolbar: https://github.com/mui-org/material-ui/blob/master/packages/material-ui/src/styles/createMixins.js

And here is the relevant excerpt from that code:

toolbar: {
      minHeight: 56,
      [`${breakpoints.up('xs')} and (orientation: landscape)`]: {
        minHeight: 48,
      },
      [breakpoints.up('sm')]: {
        minHeight: 64,
      },
    }

You can (optionally) create your own theme trough createMuiTheme. These themes and its variables (colours, default, spacings or whatever you desire) can be accessed in your styles which you add in your withstyles trough the theme arguement.

Great stuff to have the same paddings or margins anywhere for example.

Related