DEV Community

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

Posted on • Edited on

19 7

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

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

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

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay