DEV Community

Cover image for TIL - Adding Fonts to a React App
Anne Quinkenstein
Anne Quinkenstein

Posted on • Updated on

TIL - Adding Fonts to a React App

Google Fonts

Google Fonts Page

  • click on "Embed"
  • copy the link
 <link href="https://fonts.googleapis.com/css2?family=Roboto:ital,wght@1,100&display=swap" rel="stylesheet"> 
Enter fullscreen mode Exit fullscreen mode
  • go to the the public - folder, add it in index.html to the <header>

HTML

Downloaded Fonts

Create a Fonts-folder in the source directory

.src/fonts
Enter fullscreen mode Exit fullscreen mode

Copy the fonts you want to use (e.g. AssistantRegular.ttf) into the ‘fonts‘ directory.

In the project’s index.js, import the fonts you want to use.

import './fonts/assistant.regular.ttf'; 
Enter fullscreen mode Exit fullscreen mode

In the projects index.css add the font-face

@font-face {
  font-family: "AssistantRegular";
  src: local("AssistantRegular"),
    url("./fonts/assistant.regular.ttf") format("truetype");
  font-weight: normal;
}
Enter fullscreen mode Exit fullscreen mode

.woff -> format("woff"),
.ttf -> format("truetype")
.eot -> format('embedded-opentype')
.svg#vtks_sonhoregular _> format('svg')

Now the font/s are available to the project and can be used in regular CSS etc

.body {
  font-family: AssistantRegular
  ...
}
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
yaireo profile image
Yair Even Or

why do you need to import the font file in a javascript?
seems like weird step

import './fonts/assistant.regular.ttf'; 
Enter fullscreen mode Exit fullscreen mode

There are webpack loaders which will do it automatically, this this one:
npmjs.com/package/resolve-url-loader

@font-face {
  font-family: "AssistantRegular";
  src: local("AssistantRegular"),
    url("./fonts/assistant.regular.ttf") format("truetype");
  font-weight: normal;
}
Enter fullscreen mode Exit fullscreen mode