Elegant way to use variable font with MUI

Viewed 314

So I'm using MUI v5 and I'm using variable fonts as well.

Currently, my implementation of the theme is quite ugly in my opinion.

typography: {
    fontFamily: systemFonts.join(","),
    fontWeightExtraBold: 800,
    h1: {
      fontSize: "clamp(2.625rem, 1.2857rem + 3.5714vw, 4rem)",
      fontWeight: 800,
      lineHeight: 78 / 70,
      "@supports (font-variation-settings: normal)": {
        fontFamily: variableSystemFonts.join(","),
        fontVariationSettings: "'wght' 800"
      }
    },
    h2: {
      fontSize: "clamp(1.5rem, 0.9643rem + 1.4286vw, 2.25rem)",
      fontWeight: 800,
      lineHeight: 44 / 36,
      "@supports (font-variation-settings: normal)": {
        fontFamily: variableSystemFonts.join(","),
        fontVariationSettings: "'wght' 800"
      }
    },
    h3: {
      fontSize: defaultTheme.typography.pxToRem(36),
      lineHeight: 44 / 36,
      letterSpacing: 0,
      "@supports (font-variation-settings: normal)": {
        fontFamily: variableSystemFonts.join(",")
      }
    },
    // ...
  }

Basically, I have to specify

"@supports (font-variation-settings: normal)": {
  fontFamily: variableSystemFonts.join(",")
}

For every single typography variant.

I'm wondering is there a more elegant, cleaner way to achieve what I'm trying to do?

1 Answers

Maybe you can put it in a factory function (Not tested yet):

const normalVariation = (extraProperties) => ({
  "@supports (font-variation-settings: normal)": {
    fontFamily: variableSystemFonts.join(","),
    ...extraProperties,
  }
})
typography: {
    fontFamily: systemFonts.join(","),
    fontWeightExtraBold: 800,
    h1: {
      fontSize: "clamp(2.625rem, 1.2857rem + 3.5714vw, 4rem)",
      fontWeight: 800,
      lineHeight: 78 / 70,
      ...normalVariation({
        fontVariationSettings: "'wght' 800",
      })
    },
    h2: {
      fontSize: "clamp(1.5rem, 0.9643rem + 1.4286vw, 2.25rem)",
      fontWeight: 800,
      lineHeight: 44 / 36,
      ...normalVariation({
        fontVariationSettings: "'wght' 800",
      })
    },
    h3: {
      fontSize: defaultTheme.typography.pxToRem(36),
      lineHeight: 44 / 36,
      letterSpacing: 0,
      ...normalVariation(),
    },
    // ...
  }
Related