Solution
To use font face in styled component, you have to import create globlestyle
from style component and with in createGlobalStyle
. You have to mention @font-face
thats how you can use font face in style component.
For google font, first of all you have to type google font on google.
Here choose the font of your choice, Select its boldness and italic.
When you click on the download button
it is downloaded in a zip file
, then it is opened in the extract to
folder. Copy this font file and paste in your folder and then use the fonts.
When you download google Fonts, create a new folder
to put it in the src
section and then save the file
.
We need to import createGlobalStyle
from Styled Components.
import { createGlobalStyle } from "styled-components";
Snippet
In this snippet, we will see the GlobalStyle
component is created using createGlobalStyle
and it defines some css styles .@font-face
.
const FontStyles = createGlobalStyle`
@font-face {
font-family: 'Dancing Script', cursive;
src: url(${Dancing}) format('ttf'),
url(${Dancing}) format('ttf');
}
h1, h2 {
font-family: 'Dancing Script', cursive;
}
`;
Example
In this example, you have to Imported a file named 'DanceScript-VariableFont_wght.ttf'
from the folder named ./fonts
and use css name @font-face
and font-family: 'Dancing Script', cursive;
.
Let’s start coding…
App.js
import { createGlobalStyle } from "styled-components";
import Dancing from "./fonts/DancingScript-VariableFont_wght.ttf";
const FontStyles = createGlobalStyle`
@font-face {
font-family: 'Dancing Script', cursive;
src: url(${Dancing}) format('ttf'),
url(${Dancing}) format('ttf');
}
h1, h2 {
font-family: 'Dancing Script', cursive;
}
`;
export default function ComboBox() {
return (
<>
<FontStyles />
<h1>How to import font in styled components</h1>
<h2>How to import font in styled components</h2>
</>
);
}
Output
Links
Here, we are provided code sandbox links for the above program use font face in styled components. then you can use whenever you went and do the changes as per your requirements.
Happy Coding,
I hope the above example with help you to do your task.