Jordan
Jordan

Reputation: 2523

Use theme.spacing function in override in createMuiTheme

Is there a preferred way to use the theme spacing when setting up the the theme with createMuiTheme? I've been hard coding these values and for the most part there hasn't been an issue since most of my projects don't override the default theme spacing, but it would be nice to be able to use the theme spacing in my overrides?

Upvotes: 7

Views: 1558

Answers (2)

Michael Lynch
Michael Lynch

Reputation: 3159

TypeScript

import { Theme } from '@mui/material';

interface StyleOverridesParams {
  theme: Theme
}

export default createTheme({
  components: {
    MuiAppBar: {
      styleOverrides: {
        root: ({ theme }: StyleOverridesParams) => ({
          margin: theme.spacing(2)
        })
      }
    }
  }
})

ownerState, "the combination of runtime props and internal states" for the component, is also available in the callback.

https://mui.com/blog/callback-support-in-style-overrides/

Upvotes: 0

Jordan
Jordan

Reputation: 2523

This is resolved in the new Mui v5 by using a function passed to a style name

export default createTheme({
  components: {
    MuiAppBar: {
      styleOverrides: {
        root: ({ theme }) => ({
          margin: theme.spacing(2)
        })
      }
    }
  }
})

Upvotes: 7

Related Questions