Home > database >  Creating an attribute for theme Typography in MUI and typescript
Creating an attribute for theme Typography in MUI and typescript

Time:11-03

I have the following code which for the palette works but for the typography doesn't, although it doesn't throw an error:

Step by step:

  1. Import the module
import "@mui/material/styles/createTypography";
  1. Declare it and create the additional option
declare module "@mui/material/styles/createTypography" {
  interface TypographyOptions {
    tab?: React.CSSProperties;
  }
}
  1. add the option to the theme:
const theme = createTheme({
  typography: {
    h3: {
      fontWeight: typographyFonts.H3,
      // color: themePalette.ARCBLUE,
    },
    tab: {
      fontFamily: "Raleway",
    },
  },
});

I don't get an error here, which I did before, but when I build a component and use it I get an error that "tab" does not exist:

This is how I use it in the other component for styling

const StyledTab = styled(Tab)(() => ({
  ...theme.typography,
  textTransform: "none",
  fontWeight: "700",
  fontSize: "1rem",
  minWidth: 10,
  marginLeft: "25px",
}));

CodePudding user response:

The makeStyles function argument has a parameter that you can use:

const useStyles = makeStyles((theme: Theme) => ({
  logo: {
    height: "5em",
  },
  tabsContainer: {
    ...theme.typography.tab,
    marginLeft: "auto",
    color: "white",
  },
}));

or (you updated the code as I was writing):

const StyledTab = styled(Tab)((theme: Theme) => ({
  ...theme.typography,
  textTransform: "none",
  fontWeight: "700",
  fontSize: "1rem",
  minWidth: 10,
  marginLeft: "25px",
}));

Also, ensure your application is wrapped in :

<ThemeProvider theme={theme}>
   ...
</ThemeProvider>

Also if your using v5, your overrides should look like this:

declare module '@mui/material/styles' {
  interface TypographyVariants {
    tab: React.CSSProperties;
  }

  // allow configuration using `createTheme`
  interface TypographyVariantsOptions {
    tab?: React.CSSProperties;
  }
}

// Update the Typography's variant prop options
declare module '@mui/material/Typography' {
  interface TypographyPropsVariantOverrides {
    tab: true;
  }
}

  • Related