When I first set out to import a font into my React component, I thought it would be pretty straightforward. While the solution was pretty simple, it took a little bit of research to discover what was needed.

For context, in my situation, I was trying to get a font registered in the @react-pdf/renderer package. I’m using Create React App (CRA) and Typescript.

The first thing we need to do is download and add the font file to our source files. My first instinct was to add the file to the /public folder, but this is not the recommended way from the CRA docs. Instead, I added the file as follows:

src
|-- assets
|   |-- fonts
|   |   |-- Montserrat-Regular.ttf

Then it should just be a matter of importing the file into our component, right? Just like with images or CSS files?

// file: src/components/pdf/my-pdf-doc/my-pdf-doc.tsx

import montserrat from "../../../assets/fonts/Montserrat-Regular.ttf";

Yes and no. It’s not wrong, but Typescript needs another step.

If you’ve tried this already, then you have most likely run into this error:

TS2307: Cannot find module '../../../assets/fonts/Montserrat-Regular.ttf' or its corresponding type declarations.

This is where I got thrown off. I’m not a total beginner with Typescript, but I’m definitely still learning – so I wasn’t aware that you need to declare the font file format as a module so Typescript can handle the import (thank you to Bradly Locking for this Stack Overflow answer!).

The Solution

We need to add a declaration file, and tell Typescript that .ttf files can be imported as modules. I did so as follows:

// file: src/assets/fonts/fonts.d.ts

declare module "*.ttf";

One line, and we’re good to go! Typescript now recognizes the .ttf file, and the error should now be cleared up.

Result – File Structure and Code

For the sake of completion, here was the end result:

src
|-- assets
|   |-- fonts
|   |   |-- fonts.d.ts
|   |   |-- Montserrat-Regular.ttf
|-- components
|   |-- pdf
|   |   |-- my-pdf-doc
|   |   |   |-- my-pdf-doc.tsx

And the code to import the font, and register it with @react-pdf/renderer:

import montserrat from "../../../assets/fonts/Montserrat-Regular.ttf";
import { Font } from "@react-pdf/renderer";

Font.register({
  family: "Montserrat",
  src: montserrat,
});

1 Comment

Leave a Reply