Search code examples
cssreactjsstylesgoogle-fonts

How to use Google Fonts API in React JS?


I am trying to set Google Fonts in my React project but I am not being able to override the original font families of React.

Following some tutorials I inserted the font-family I want into index.css:

body {
  /* margin: 0;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Lemonada'
    'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
    sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale; */
  font-family: 'Lemonada', 
    cursive;
}

I commented the original fonts for testing purposes.

However the original fonts are not being overwritten:

enter image description here

If I inspect the file I see this:

enter image description here

As you can see all the commented fonts are still there, besides there are a lot of other things that doesn't exist in index.css. Apparently it is coming from some style.css file, but I have no idea where to find this.

If I uncheck this style I get the font-family I want:

enter image description here enter image description here

And of course, I also added the api to my index.html file.

<link href="https://fonts.googleapis.com/css2?family=Lemonada:wght@300&display=swap" rel="stylesheet">

I'd like to be able to add new font-families or at least override the original ones.

What am I doing wrong?


Solution

  • I kept digging and I found two possible solutions:

    1- Instead of using the index.css, I put the font-family direct inside the css file corresponding to the component I want to use the font, in this case this is the file Layout.css.

    2- I found out this library and it also works and seems to be very great: https://www.npmjs.com/package/react-google-font-loader