Solution

To import font in styled components, first you have to put font file in your project font directory .Then use react import statement to import font file and use it in your style css.

For google font, first of all you have to type google font on google.

import, fonts

Here choose the font of your choice, Select its boldness and italic.

import, fonts

When you click on the download button it is downloaded in a zip file, then it is opened in the extrat to folder. Copy this font file and paste in your folder and then use the fonts.

import, fonts

When you download google Fonts, create a new folder to put it in the src section and then save the file.

import, fonts

We need to import createGlobalStyle from Styled Components.

import { createGlobalStyle } from "styled-components";

Snippet

In this snippet, we will see the GlobalStyle component is created using createGlobalStyle and it defines some css styles .@font-face.

const FontStyles = createGlobalStyle`

@font-face {
  font-family: 'Dancing Script', cursive;
  src: url(${Dancing}) format('ttf'),
  url(${Dancing}) format('ttf');
      
}

  h1, h2 {
    font-family: 'Dancing Script', cursive;
  }
`;

Example

In this example, you have to Imported a file named 'DanceScript-VariableFont_wght.ttf' from the folder named ./fonts and use css name @font-face and font-family: 'Dancing Script', cursive;.

Let’s start coding…

App.js

import { createGlobalStyle } from "styled-components";
import Dancing from "./fonts/DancingScript-VariableFont_wght.ttf";

const FontStyles = createGlobalStyle`

@font-face {
  font-family: 'Dancing Script', cursive;
  src: url(${Dancing}) format('ttf'),
  url(${Dancing}) format('ttf');
      
}

  h1, h2 {
    font-family: 'Dancing Script', cursive;
  }
`;


export default function ComboBox() {
  return (
    <>
      <FontStyles />
      <h1>How to import font in styled components</h1>
      <h2>How to import font in styled components</h2>
    </>
  );
}

Output

import, fonts

Here, we are provided code sandbox links for the above program import font in styled components. then you can use whenever you went and do the changes as per your requirements.

codesandbox

Happy Coding,

I hope the above example with help you to do your task.