Home > Back-end >  Failed to understand how this destructuring assignment works "{ theme : {spacing} }"
Failed to understand how this destructuring assignment works "{ theme : {spacing} }"

Time:02-05

I'm trying to override the default theme in material ui v5, at first i used this :

      styleOverrides:{
        root: ({ theme }) => ({
          margin : theme.spacing(2)
        }),
      },

But then when reading the docs i saw they used this :

const lightTheme = createTheme({
  components: {
    MuiPaper: {
      styleOverrides:{
        root: ({ theme : {spacing} }) => ({
          margin : spacing(2)
        }),
      },
    },
  },
});

Here i think they destructured the the spacing function from the theme object, what i dont understand is the syntax, why not do this :

root: ({ {spacing} }) => ({
          margin : spacing(2)
        }),

Where {spacing} is like taking out the spacing() from the theme object, no ?

The ":" in { theme : {spacing} } is what confuses me, i'm not familiar with that syntax and i dont want to make assumptions on what it precisely does, i read these 2 resources

But i still couldn't find the anwer, if someone could explain it i'd be grateful.

CodePudding user response:

The parameter likely looks like { theme: { spacing: ... } }, therefore to access it you need to define the full path (theme and spacing). If you only use ({ {spacing} }) it won't know that you want to access the spacing within the theme property. For instance in the following example ({ {spacing} }) would be ambiguous, potentially meaning two different functions:

const params = {
  theme: {
    spacing: (n) => `some css: ${n}`
  },
  otherProps: {
    spacing: (n) => `other prop: ${n}`
  },
}

const v1 = (params) => params.theme.spacing(2)
const v2 = ({ theme }) => theme.spacing(2)
const v3 = ({ theme: { spacing } }) => spacing(2)

console.log(v1(params))
console.log(v2(params))
console.log(v3(params))

CodePudding user response:

{ {spacing} } won't do the trick. { theme: {spacing} } destructures two objects. First the object that is passed to the arrow function, then another object that is stored in the .theme property. In only variable that's being created here is spacing, which is .theme.spacing. Take this example:

const obj = {theme: {spacing: 1, color: 'blue'}};

const fn1 = ({theme: {spacing}}) => console.log(spacing);
fn1(obj);

  • Related