cssreactjstypescriptjss

How to use google fonts in a typescript react-app with JSS?


How do I include Google fonts so I can use them in my JSS?

const styles = ({palette, typography}: Theme) => 
  createStyles({
    time: {
      flexBasis: '10%',
      flexShrink: 0,
      fontSize: typography.pxToRem(20)
    },
    guestname: {
      flexBasis: '20%',
      flexShrink: 0,
      fontSize: typography.pxToRem(20),
    }
})

Solution

  • Go on fonts.google.com, "select the font(s)" you need. When you are finished, click the @import tab and copy the @import code only:

    @import url('https://fonts.googleapis.com/css?family=Montserrat&display=swap');
    

    paste it in your CSS file, e.g. index.css then save.

    In your JSS, to use the imported font, do:

    const styles = ({palette, typography}: Theme) => 
      createStyles({
        time: {
          flexBasis: '10%',
          flexShrink: 0,
          fontFamily: "'Montserrat', sans-serif", // <-- FONT IS USED HERE
          fontSize: typography.pxToRem(20)
        },
        guestname: {
          flexBasis: '20%',
          flexShrink: 0,
          fontSize: typography.pxToRem(20),
        }
    })