'How to use ChakraUI extended fonts

Hello I have question can I have 2 different fonts for Heading like you know you define <Heading fontFamily={???}></Heading> and set font family inside it. I do not want to have one font family for heading.

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

const theme = extendTheme({
  fonts: {
    heading: "Dancing Script",
  },
});

export default theme;


Solution 1:[1]

Yes, you can write <Heading fontFamily="myFont1"></Heading> and <Heading fontFamily="myFont2">Some Text</Heading> if you declare these two fonts in your extended theme:

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

const theme = extendTheme({
  fonts: {
    myFont1: "Dancing Script",
    myFont2: "Times New Roman",
  },
});

export default theme;

Also, notice that I didn't have to import any external library for Times New Roman (because it's likely to already be installed on you users' computer) but I had to import @fontsource/dancing-script because it's not a standard font. (Remember to install it with npm install --save @fontsource/dancing-script before you use it).

You can probably find any fonts you need on FontSource, and for more information (and alternative solutions) there is the Chakra UI documentation on fonts.

Solution 2:[2]

To add to Giorgio's answer, if you want to have as much code as possible in the theme definition, you can even declare the font for all variations of headers.

<Heading>h1 text</Heading>
<Heading as="h2">h2 text</Heading>

and then configure your theme like this:

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

const theme = extendTheme({
  fonts: {
    heading: "Dancing Script",
    subHeading: "Times New Roman",
  },
  textStyles: {
    h2: {
      'font-family': 'var(--chakra-fonts-subHeading)',
    },
  }
});

export default theme;

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) and reference the variable this way: var(--chakra-fonts-subHeading)

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 Giorgio
Solution 2