How to insert a Local Font in my Project? - reactjs

I used IconMoon to create custom icon fonts.
In the .html that is generated by it, it works perfectly. But when I try to use it in my project with React and Styled-Components, instead of being displayed the icon displays its content in HTML.
My fonts are in the path: src/assets/fonts/icons
Fonts are being downloaded by the browser and no errors are displayed:
Soon I am trying to create a component for my fonts, similar to FontAwesome and this happens:
MY COMPONENT:
import React from "react";
import styled from "styled-components";
const Tst = styled.i`
font-family: "spotify" !important;
font-style: normal;
font-weight: normal;
font-variant: normal;
text-transform: none;
line-height: 1;
::before {
content: "\e900";
color: red;
}
`;
const SaveFavorite = () => {
return <Tst />;
};
export default SaveFavorite;
MY GLOBAL STYLES:
import { createGlobalStyle } from "styled-components";
const GlobalStyle = createGlobalStyle`
#font-face {
font-family: "spotify";
font-weight: normal;
font-style: normal;
src: url("../assets/fonts/spotify.eot?") format("embedded-opentype"),
url("../assets/fonts/spotify.ttf?") format("truetype"),
url("../assets/fonts/spotify.woff?") format("woff"),
url("../assets/fonts/spotify.svg?") format("svg");
}
* {
box-sizing: border-box;
padding: 0;
margin: 0;
outline: 0;
}
body {
font-family: 'CircularSpUIv3T', sans-serif;
color: white;
text-rendering: optimizeLegibility !important;
-webkit-font-smoothing: antialiased !important;
-moz-osx-font-smoothing: grayscale !important;
user-select: none;
}
img {
width: 100%;
max-width: 100%;
height: auto;
}
`;
export default GlobalStyle;

If you look at the css generated by Styled Components, you'll find that the font paths aren't resolved at all, they are exactly the way you typed them. The browser won't be able to find relative paths in the src directory without some help from Babel, and the way you have it now these paths would just be passed as-is.
You have two options, although I'm not sure if both will work.
Option 1: move your fonts to the public directory
Files in the public directory can be found by the browser just like any old HTML page. In your global style, you would then have to use a path that is relative to public/index.html.
Your file structure would be something like:
project
|-- public
|-- index.html
|-- fonts
|-- spotify.eot
|-- spotify.ttf
|-- spotify.woff
|-- spotify.svg
|-- src
|-- global.style.js
|-- (...)
And your global.style.js:
const GlobalStyle = createGlobalStyle`
#font-face {
font-family: "spotify";
src: url("fonts/spotify.eot?") format("embedded-opentype"),
url("fonts/spotify.ttf?") format("truetype"),
url("fonts/spotify.woff?") format("woff"),
url("fonts/spotify.svg?") format("svg");
}
Option 2: keep your fonts in src, but make Babel resolve the paths for you
To make Babel resolve the paths, we need to import the files in our global.style.js, and then use the resolved path instead of the static one:
import SpotifyEOT from '../assets/fonts/spotify.eot';
// etc
const GlobalStyle = createGlobalStyle`
#font-face {
font-family: "spotify";
src: url(${SpotifyEOT}?) format("embedded-opentype"),
// [etc]
}
I don't know what the question mark is actually for but I assume you can just place it after the resolved path like I did.

Related

create-react-app based projects added font but not working

I'm using create-react-app and prefer not to eject.
i imported in index.html file . and give it default font. but its not working.
<style>
#font-face {
font-family: Gumela;
src: url("../src/fonts/*");
}
* {
font-family: "Gumela";
font-weight: normal;
font-size: 20px;
}
body {
margin: 0;
}
</style>
Try importing the fonts in your app.css or index.css file.
And try:
#font-face {
font-family: Gumela;
src: url("../src/fonts/*");
font-display: swap; // This will swap font once its loaded, for SEO purpose.
}
* {
font-family: Gumela;
font-weight: normal;
font-size: 20px;
OR
font: Gumela normal 20px;
}
I imported the font here: https://www.onlinewebfonts.com/download/00561b492d88a5287a5def1e83a34882 and it worked for me.
just add this in head before your style tag.
<link href="//db.onlinewebfonts.com/c/00561b492d88a5287a5def1e83a34882?family=Gumela" rel="stylesheet" type="text/css"/>
You can insert font-face on your App.css file
#font-face {
font-family: Gumela;
src: url('./fonts/Gumela\ Regular.otf');
}

Google fonts not applied to deployed react app on Github Pages

I'm using styled-components for my app, and I imported a google font url in createGlobalStyle. :
import { createGlobalStyle } from "styled-components";
const GlobalStyles = createGlobalStyle`
* {
#import url(//fonts.googleapis.com/css2?family=Space+Mono:wght#400;700&display=swap);
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: 'Space Mono', monospace;
font-weight: 400;
}
After deploying the app, the font is not applied. I tried replacing the #import url from https://fonts.. to http://fonts.. and then currently //fonts... These are some solutions I found that have worked for some, but not for me. What seems to be the problem here?
here is the link of the deployed app: http://patorikkun.github.io/tip-calculator-app
Try to move the #import to top level, outside * {}
From:
createGlobalStyle`
* {
#import url("https://fonts.googleapis.com/css2?family=Space+Mono:wght#400;700&display=swap");
margin: 0;
...
}
...
}`;
To:
createGlobalStyle`
#import url("https://fonts.googleapis.com/css2?family=Space+Mono:wght#400;700&display=swap");
* {
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: 'Space Mono', monospace;
font-weight: 400;
}
...
}`;
From the MDN explanation:
Imported rules must precede all other types of rules, except #charset rules;

Encountering white-space at top of react-app

enter image description here
Image
encountering white space at top of the react-app
Check the image
There's weird whitespace occurring at the top of the react-app. My developed app not even a big react-app but there something occupying the space there and creating a white space there. I have deleted the old project and did this new one thinking it'll remove my error but the same result. I'm using a routing package to route through my app react-route-dom. I tried all the possible ways but couldn't find out the error or the line of code that is triggering the white-space at the top of the react-app. Please anyone help I have to submit my project!.
App.js
import React from 'react'
import './App.css';
function App() {
return (
<div className="App">
<h1>Hello</h1>
</div>
);
}export default App
App.css
.App {
text-align: center;
background: red;
height: 30%;
}
Index.js
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import { BrowserRouter } from 'react-router-dom'
const app = <BrowserRouter><App/></BrowserRouter>
ReactDOM.render(
<React.StrictMode>
{app}
</React.StrictMode>,
document.getElementById('root') );
reportWebVitals()
**index.css**
body {
margin: 0;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
background: #333;
}
code {
font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',
monospace;
}
Add this to your index.css :
*{
margin: 0;
padding: 0;
box-sizing: border-box; // not neccesary
}
This happens because chrome by default adds some padding to your page
user agent stylesheet is doing that. For instance Chrome styles h1 by default like so:
h1 {
display: block;
font-size: 2em;
margin-block-start: 0.67em;
margin-block-end: 0.67em;
margin-inline-start: 0px;
margin-inline-end: 0px;
font-weight: bold;
}
This will create those margins you're complaining about. All you need to do is explicitly style your h1 in your CSS file. Something like this: h1{margin: 0px}. Do the same for the body.
Also note that If <!DOCTYPE> is missing in your HTML content oftentimes the browser gives preference to the "user agent stylesheet" over your custom stylesheet.
In my case, the space provoked the css property place-items: center from the index.css file.

Why is my local font not being applied with Emotion global styling?

I am trying to use a locally hosted font in a React project that utilizes Emotion, and its Global component. This method works great for web fonts, like Google Fonts, but when I downloaded that same font and tried to apply it as a local .ttf file using #font-face, I couldn't achieve the same result.
Here's the important file, App.js:
import React from "react";
import { Global, css } from "#emotion/core";
import styled from "#emotion/styled";
const GlobalStyles = css`
#import url("https://fonts.googleapis.com/css?family=Dancing+Script&display=swap");
#font-face {
font-family: "Local Font";
src: url("fonts/DancingScript-Regular.ttf");
}
* {
text-align: center;
}
`;
const FromGoogle = styled.h1`
font-family: "Dancing Script";
`;
const FromLocal = styled.h1`
font-family: "Local Font";
`;
function App() {
return (
<div className="App">
<Global styles={GlobalStyles} />
<FromGoogle>This text's font family is from Google.</FromGoogle>
<FromLocal>
This text's font family should be the same, except it comes from a local
font file, and it's not working.
</FromLocal>
</div>
);
}
export default App;
For some reason, the text in FromGoogle uses the Google font fine, while the text from FromLocal doesn't. My first thought was that it's an issue with the path, but if it is, I couldn't tell.
Here's the full project on GitHub. I used Create React App, and removed all the irrelevant boilerplate.
In my Next.js app I am using emotion with these versions:
"#emotion/react": "^11.1.1",
"#emotion/styled": "^11.0.0",
My global styles are:
export const GlobalStyles = () => (
<Global
styles={css`
#font-face {
font-family: 'Faustina';
font-style: normal;
font-weight: 700;
src: local(''),
url('/fonts/Faustina/Faustina.woff') format('woff'),
url('/fonts/Faustina/Faustina.ttf') format('truetype');
}
* {
box-sizing: border-box;
font-family: Faustina;
}
html,
body {
width: 100%;
height: 100%;
min-height: 100%;
padding: 0;
margin: 0;
}
`}
/>
);
My fonts are in
project_root/public/fonts/Faustina
// explicitly
project_root/public/fonts/Faustina/Faustina-Bold.ttf
project_root/public/fonts/Faustina/Faustina-Bold.woff
In order to see font changes, I needed to restart dev server, e.g. yarn dev. Before restarting I had same issue where fonts weren't displayed (even downloaded in dev tools Network tab).
am using these versions in my gatsby project;
"#emotion/react": "^11.8.1",
"gatsby": "^4.8.0"
index.html file is not available so you can't add <style> html tag and embed #font-face inside it.
Host your downloaded fonts inside your src/myfonts directory then import any of your fonts using the static import statement.
import font1 from './myfonts/font1.ttf';
then call url(font1) css function with the font1
const globalStyle = css`
#font-face {
font-family: 'font1';
src: url(${font1}) format('truetype');
};
`;
it worked in my case;
In my case, the solution was as in this answer.
I needed to define the fonts in a css file that is imported into the index.html like so:
<link rel="stylesheet" type="text/css" href="/styles/fonts.css" />
I was then able to reference the font family names in my emotion theme and have them load correctly.

How do I add base styling for entire app with "Styled-components"?

So let's say I have some base styling for the app like:
:root {
--color-primary: #eb2f64;
--color-primary-light: #FF3366;
--color-primary-dark: #BA265D;
}
* {
margin: 0;
padding: 0;
}
*,
*::before,
*::after {
box-sizing: inherit;
}
html {
box-sizing: border-box;
font-size: 16px;
}
body {
font-family: 'Open Sans', sans-serif;
font-weight: 400;
line-height: 1.6;
background-image: linear-gradient(to right bottom, var(--color-primary-light), var(--color-primary-dark));
background-size: cover;
}
I want to use "Styled-components" library but wondering how do I add these base styles to my app without touching any external .scss file? Or should I create base.scss file and do import './base.scss'; to index.js?
It doesn't allow me to do smth like this:
const Wrapper = styled.html`
box-sizing: border-box;
font-size: 16px;
`;
I get an error because of that html element
Aha. Found it: import { injectGlobal } from 'styled-components';

Resources