Gildas Garcia
Gildas Garcia

Reputation: 7066

Theme override support for custom components

After the migration to mui v5 for react-admin, we realized that supporting theme overrides for our custom components seems to require more code than we expected. As it looks that this could be handled by the styled API, I would like to know if this is really required.

Here's an example of our Navigation link:

const PREFIX = 'RaMenuItemLink';

export const MenuItemLinkClasses = {
    root: `${PREFIX}-root`,
    active: `${PREFIX}-active`,
    icon: `${PREFIX}-icon`,
};

const StyledMenuItem = styled(MenuItem, {
    name: PREFIX,
    // Why do I have to do this?
    overridesResolver: (props, styles) => [
        { [`&.${MenuItemLinkClasses.active}`]: styles.active },
        { [`& .${MenuItemLinkClasses.icon}`]: styles.icon },
        styles.root,
    ],
})(({ theme }) => ({
    [`&.${MenuItemLinkClasses.root}`]: {
        color: theme.palette.text.secondary,
    },

    [`&.${MenuItemLinkClasses.active}`]: {
        color: theme.palette.text.primary,
    },

    [`& .${MenuItemLinkClasses.icon}`]: { minWidth: theme.spacing(5) },
}));

Upvotes: 1

Views: 404

Answers (1)

Olivier Tassinari
Olivier Tassinari

Reputation: 8681

In your case, I think that I would start to simplify the code to:

const PREFIX = 'RaMenuItemLink';

export const MenuItemLinkClasses = {
    root: `${PREFIX}-root`,
    active: `Mui-active`,
    icon: `${PREFIX}-icon`,
};

const StyledMenuItem = styled(MenuItem, {
    name: PREFIX,
    overridesResolver: (props, styles) => [
        styles.root,
        { [`&.${MenuItemLinkClasses.active}`]: styles.active },
        { [`& .${MenuItemLinkClasses.icon}`]: styles.icon },
    ],
})(({ theme }) => ({
    color: theme.palette.text.secondary,

    [`&.${MenuItemLinkClasses.active}`]: {
        color: theme.palette.text.primary,
    },

    [`& .${MenuItemLinkClasses.icon}`]: { minWidth: theme.spacing(5) },
}));

The overridesResolver property is meant to resolve this object:

const theme = {
  components: {
     [PREFIX]: {
        styleOverrides: /* this object, it's the 'styles' arg of overridesResolver */,
     },
  },
};

Upvotes: 2

Related Questions