'Using fonts in chakra UI in Next js

My application is built using NextJs and uses Chakra UI. I have installed Google Fonts by following this

chakra Google fonts

npm install @fontsource/open-sans @fontsource/raleway

import { extendTheme } from "@chakra-ui/react"

const theme = extendTheme({ fonts: { heading: "Open Sans", body: "Raleway", }, })

export default theme

Now I can use two different fonts,

  1. For Body
  2. For headings

However, how about using more fonts ? Say I was to use different fonts for Buttons, Different for Text. Also within text, I want to use different fonts for Italic and underlined text portions.

How do I do that ?



Solution 1:[1]

It is pretty easy to add more fonts using the theme, you just need to add them in fonts: {} and then you can reference them by using the chakra variable: var(--chakra-fonts-xxx)

For example, if you want to define a font dedicated to subheader:

import { extendTheme } from "@chakra-ui/react";

const theme = extendTheme({
  fonts: {
    heading: "Open Sans",
    subHeading: "Times New Roman",
    body: "Arial Black",
  },
  textStyles: {
    h2: {
      'font-family': 'var(--chakra-fonts-subHeading)',
    },
  }
});

export default theme;

Now when you'll create a h2 component (<Heading as="h2">h2 text</Heading>), it will use this font.

You'll notice that unfortunately, I had to use 'font-family' instead of fontFamily (it seems to be an existing bug, same for font-weight).

Solution 2:[2]

To use different fonts in Buttons, you can customize Buttons components from your theme. in const theme, the same way as fonts you need to create a components object:

const theme = extendTheme({ 
    fonts: { 
        heading: "Open Sans", body: "Raleway", 
    }, 
    components: {
        Button: {
            baseStyle: {
                fontFamily: 'yourfont here'
            }
        }
    }
})

You can do the same with other state of buttons for example _hover, _focus, _isDisabled, etc.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 SamHecquet
Solution 2 juliomalves