In this section, we'll explore how to incorporate custom fonts in your React application using Google Fonts, external font files, and npm packages.
index.html
Add the Google Fonts link tags directly to your public/index.html
file:
<!-- public/index.html -->
<head>
<title>React App</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Arvo&display=swap" rel="stylesheet">
</head>
Alternatively, you can import Google Fonts in your CSS files like src/index.css
or src/App.css
:
/* src/index.css or src/App.css */
@import url('https://fonts.googleapis.com/css2?family=Arvo&display=swap');
body {
font-family: 'Arvo', serif;
}
To use custom font files, follow these steps:
Download the Font Files
Download the font files (e.g., .ttf
or .woff
) and place them in a directory within your project, such as src/assets/fonts
.
Import and Use the Font
Define the font-face in your CSS file and use it:
/* src/App.css */
@font-face {
font-family: 'MyCustomFont';
src: url('./assets/fonts/MyCustomFont.ttf') format('truetype');
}
body {
font-family: 'MyCustomFont', sans-serif;
}
Some popular fonts are available as npm packages. For example, you can use the typeface-roboto
package:
Install the Font Package
npm install typeface-roboto
Import the Font in Your Project
Import the font in your main JavaScript file, such as src/index.js
:
// src/index.js
import 'typeface-roboto';
// Your other imports and React code...
Use the Font in Your CSS
/* src/App.css */
body {
font-family: 'Roboto', sans-serif;
}
Using npm packages for fonts can be convenient for managing dependencies and ensuring consistent font usage across your project.
Objective: Integrate Google Fonts, an external font file, and a font npm package into a React application.
Add Google Font (Arvo) via Link Tag:
public/index.html
:<head>
<title>React App</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Arvo&display=swap" rel="stylesheet">
</head>
src/App.css
:body {
font-family: 'Arvo', serif;
}
Add an External Font File:
Download a font file and place it in src/assets/fonts
.
Define and use the font in src/App.css
:
@font-face {
font-family: 'MyCustomFont';
src: url('./assets/fonts/MyCustomFont.ttf') format('truetype');
}
body {
font-family: 'MyCustomFont', sans-serif;
}
Add a Font Using an npm Package:
typeface-roboto
:npm install typeface-roboto
src/index.js
:import 'typeface-roboto';
// Your other imports and React code...
src/App.css
:body {
font-family: 'Roboto', sans-serif;
}
This task will help you practice adding different types of fonts to a React application.