material-ui: [IconButton] Custom non-palette color causes TypeError

Duplicates

  • I have searched the existing issues

Latest version

  • I have tested the latest version

Current behavior 😯

When I augment IconButton with new colors that don’t exist in the palette:

declare module "@mui/material/IconButton" {
  interface IconButtonPropsColorOverrides {
    textPrimary: true;
    textSecondary: true;
  }
}

and then try to use these colors:

<IconButton color="textPrimary">
  <CloseIcon />
</IconButton>

My app crashes with:

TypeError: Cannot read properties of undefined (reading 'main') 

at the following location:

https://github.com/mui/material-ui/blob/dec32b361714bed9c73ee1360c4b6390769bf9f5/packages/mui-material/src/IconButton/IconButton.js#L78

Expected behavior 🤔

IconButton doesn’t throw TypeError when using custom color. Instead it handles it safely, like SvgIcon:

https://github.com/mui/material-ui/blob/dec32b361714bed9c73ee1360c4b6390769bf9f5/packages/mui-material/src/SvgIcon/SvgIcon.js#L54

Steps to reproduce 🕹

No response

Context 🔦

We intend for color="textPrimary" (or color="text.primary", both are fine) to use the text.primary palette color.

Workaround: pass the color to the icon component instead and augment SvgIconPropsColorOverrides typings:

<IconButton>
  <CloseIcon color="textPrimary" />
</IconButton>

Your environment 🌎

No response

About this issue

  • Original URL
  • State: closed
  • Created 2 years ago
  • Comments: 39 (22 by maintainers)

Most upvoted comments

The PR to fix this issue should:

  • custom color works with TypeScript
  • make sure that the custom color does not crash
  • add a demo to show that the color prop can be augmented

@ZeeshanTamboli if you are available, this could be one to pick up.

@harsh5902 you can take it over

@kushagra010 I started working on it.

Hi anyone still working on this? I’d like to take it. @emlai @cyberGHostJs @hilalsidhic

Hi is anyone working one this .I’d like to take it. @emlai

@Shubhamchinda @emlai

Any progress? Would love to implement this PR

@geraldaddey Give me a day, and I’ll submit a PR.

The customization capability is not complete. I marked this as an enhancement.

The fix can use optional chaining like in SvgIcon. However, please note that when you customize the color prop, you are opting out of the theme palette so you have to style by:

createTheme({
  components: {
    MuiIconButton: {
      root:  ({ ownerState, theme }) => ({
        ...ownerState.color === 'textPrimary' && {
          // your style
        }
      })
    }
  }
})