Search code examples
javascriptreactjsfontsstylingchakra-ui

Primary and secondary font with Chakra UI


I am using Chakra Ui with React and I am trying to use two different fonts for two components, I already imported them using the Global method described in the docs but how can I use only the secondary one in my current component?


Solution

  • When you mean secondary one, I am assuming that this is your secondary font? If so, there are two things you should be aware of. It is the textStyles key and extendTheme function from Chakra UI:

    1. Import the extendTheme function imported from Chakra UI.

      import { extendTheme } from "@chakra-ui/react"
      
    2. Using the extendTheme function will allow you to add new styles. This is where you will place the textStyles key:

      const themeExample = extendTheme({
          // Whatever you pass here will be ADDED to the theme.
          textStyles: { 
              primary: {
                  fontFamily: "Font Primary"
              },
              secondary: {
                  fontFamily: "Font Secondary"
              },
          },
      });
      
    3. Now the desired fonts are set up, they are easily accessible:

      <Box textStyle='primary'>Component One</Box>
      <Box textStyle='secondary'>Component Two</Box>
      

    More information can be found here: https://chakra-ui.com/docs/features/text-and-layer-styles