I'm trying to get fonts to work in React
with TypeScript
and styled-components
.
The GlobalStyle.ts
looks the following:
import { createGlobalStyle } from "styled-components";
const GlobalStyle = createGlobalStyle`
@font-face {
font-family: 'Roboto';
font-style: normal;
font-weight: 300;
src: url('./fonts/roboto-v27-latin-300.eot'); /* IE9 Compat Modes */
src: local(''),
url('./fonts/roboto-v27-latin-300.eot?#iefix') format('embedded-opentype'), /* IE6-IE8 */
url('./fonts/roboto-v27-latin-300.woff2') format('woff2'), /* Super Modern Browsers */
url('./fonts/roboto-v27-latin-300.woff') format('woff'), /* Modern Browsers */
url('./fonts/roboto-v27-latin-300.ttf') format('truetype'), /* Safari, Android, iOS */
url('./fonts/roboto-v27-latin-300.svg#Roboto') format('svg'); /* Legacy iOS */
}
*{
color: red;
font-family: "Roboto";
}
`;
export default GlobalStyle;
My index.tsx
looks like this:
import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
import GlobalStyle from "./GlobalStyle";
ReactDOM.render(
<React.StrictMode>
<GlobalStyle />
<App />
</React.StrictMode>,
document.getElementById("root")
);
I removed some lines from both files that were unnecessary in this context. Both files are at the same level in the directory. The files for the fonts are all downloaded in a folder called "fonts"
"Normal" styling works like the "color: red;" in GlobalStyles.ts
.
However, I simply cannot get the font to load. Does anyone know how to fix this? If you need any more information, just tell me and I will provide it!
Styled component structure and syntax looks fine.
Webfont files need to be in the public
folder outside src
(since they’re not being imported directly into the component the way you might with an image asset or a static css file for example). The CSS rules pointing at font urls will ultimately be relative to where the <style>
tag is being inserted in the DOM, not relative to your React project folder structure. So you may need to update your url
values after you’ve moved your fonts.
Also, unless you really need to support legacy browsers, you really only need woff2
format.