I had built a website with React.js and webpack.
I want to use Google fonts in the webpage, so I put the link in the section.
In some sort of main or first loading CSS file, just do:
@import url('https://fonts.googleapis.com/css?family=Source+Sans+Pro:regular,bold,italic&subset=latin,latin-ext');
You don't need to wrap in any sort of @font-face, etc. the response you get back from Google's API is ready to go and lets you use font families like normal.
Then in your main React app JavaScript, at the top put something like:
import './assets/css/fonts.css';
What I did actually was made an app.css
that imported a fonts.css
with a few font imports. Simply for organization (now I know where all my fonts are). The important thing to remember is that you import the fonts first.
Keep in mind that any component you import to your React app should be imported after the style import. Especially if those components also import their own styles. This way you can be sure of the ordering of styles. This is why it's best to import fonts at the top of your main file (don't forget to check your final bundled CSS file to double check if you're having trouble).
There's a few options you can pass the Google Font API to be more efficient when loading fonts, etc. See official documentation: Get Started with the Google Fonts API
Edit, note: If you are dealing with an "offline" application, then you may indeed need to download the fonts and load through Webpack.
you should see this tutorial: https://scotch.io/@micwanyoike/how-to-add-fonts-to-a-react-project
import WebFont from 'webfontloader';
WebFont.load({
google: {
families: ['Titillium Web:300,400,700', 'sans-serif']
}
});
I just tried this method and I can say that it works very well ;)
Had the same issue. Turns out I was using "
instead of '
.
use @import url('within single quotes');
like this
not @import url("within double quotes");
like this
In your CSS file, such as App.css in a create-react-app, add a fontface import. For example:
@fontface {
font-family: 'Bungee Inline', cursive;
src: url('https://fonts.googleapis.com/css?family=Bungee+Inline')
}
Then simply add the font to the DOM element within the same css file.
body {
font-family: 'Bungee Inline', cursive;
}
I added the @import and the @font-face in my css file and it worked.
In some cases your font resource maybe somewhere in your project directory. So you can load it like this using SCSS
$list: (
"Black",
"BlackItalic",
"Bold",
"BoldItalic",
"Italic",
"Light",
"LightItalic",
"Medium",
"MediumItalic",
"Regular",
"Thin",
"ThinItalic"
);
@mixin setRobotoFonts {
@each $var in $list {
@font-face {
font-family: "Roboto-#{$var}";
src: url("../fonts/Roboto-#{$var}.ttf") format("ttf");
}
}
}
@include setRobotoFonts();