Solution
To use google fonts
in styled components, you have to download google font and save your in project font directory.Then use react import statement to import font file
and use it in your style css.
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 copy the google font link
, put it within the <head>
section of your index.html
file. Which is inside the public folder
.
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 GlobalStyle
for the body element.
const GlobalStyle = createGlobalStyle`
body {
font-family: 'Sofia Sans Condensed', sans-serif;
}
`;
Example
In this example, you can use the createGlobalStyle
function from the styled-components. we will use google font
and @import
css class and add body element and use font-family: 'Sofia Sans Condensed', sans-serif;
.
Let’s start coding…
App.js
import { createGlobalStyle } from "styled-components";
const GlobalStyle = createGlobalStyle`
@import url('https://fonts.googleapis.com/css2?family=Dancing+Script:wght@600;700&family=Sofia+Sans+Condensed&family=Sofia+Sans:wght@100;300&display=swap');
body {
font-family: 'Sofia Sans Condensed', sans-serif;
}
`;
function App() {
return (
<div>
<GlobalStyle />
<h1>How to use google fonts in styled components</h1>
<h2>How to use google fonts in styled components</h2>
</div>
);
}
export default App;
Output
Links
Here, we are provided code sandbox links for the above program use google fonts 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.