How to use the Google fonts in React.js
In this tutorial, we are going to learn about how to add and use the google fonts to the react.js app with the help of examples.
Using the Google fonts locally
-
Create a new folder called fonts in your src folder.
-
Download the google fonts locally and place them inside the fonts folder.
-
Open your index.css file and include the font by referencing the path.
@font-face {
font-family: 'Rajdhani';
src: local('Rajdhani'), url(./fonts/Rajdhani/Rajdhani-Regular.ttf) format('truetype');
}
Here I added a Rajdhani font.
Now, we can use our font in css classes like this.
.title{
font-family: Rajdhani, serif;
color: #0004;
}
Using Google fonts from url
You can also use the google fonts with the help of google api instead of downloading the fonts locally.
Here is an example:
-
Open the google fonts website and choose the fonts you need.
-
Select the font weights, then copy and import url.
-
Add the following google fonts url to your main
index.css
file.
@import url('https://fonts.googleapis.com/css2?family=Rajdhani:wght@300;500&display=swap');
Now, we can use our Rajdhani
font in css classes like this.
.title{
font-family: Rajdhani, serif;
color: #0004;
}
Similarly, you can also add it inside the index.html
file using link tag.
<link href="https://fonts.googleapis.com/css2?family=Rajdhani:wght@300;500&display=swap" rel="stylesheet">
Note: The above tag should be placed inside the <head>
tag.