user10104341
user10104341

Reputation:

React - How to use GlobalStyles for Google Fonts with Emotion

I am using Emotion, as my css-in-js and I admit, I am fairly new to it. I have spend 1+. hour, to figure out how to inject global styles, and add a google font, to my entire app.

I tried:

Can someone give me a working example, please?? I want to. learn CSS IN JS, but this is getting weird. So much time, for something so simple.

Upvotes: 1

Views: 3642

Answers (3)

Dhika TB
Dhika TB

Reputation: 31

this works for me. using emotion 11

import { css, Global } from '@emotion/react';

function WithGoogleFont() {
  return (
     <Global
        styles={[
           css`
              @import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;900&display=swap');
           `,
           {
              body: { fontFamily: 'Inter' },
           },
        ]}
     />
  );
}

You have to include the font-family afterward to make it work.

Upvotes: 1

Vasyl Gutnyk
Vasyl Gutnyk

Reputation: 5039

just in case. Simplest solution is just to add it with regular css :)

Upvotes: -1

tmhao2005
tmhao2005

Reputation: 17514

I think there are two ways you can do:

  • Use injectGlobal exported from emotion:
import { injectGlobal } from 'emotion'

injectGlobal`
  @font-face {
    font-family: 'Patrick Hand SC';
    font-style: normal;
    font-weight: 400;
    src: local('Patrick Hand SC'),
      local('PatrickHandSC-Regular'),
      url(https://fonts.gstatic.com/s/patrickhandsc/v4/OYFWCgfCR-7uHIovjUZXsZ71Uis0Qeb9Gqo8IZV7ckE.woff2)
        format('woff2');
    unicode-range: U+0100-024f, U+1-1eff,
      U+20a0-20ab, U+20ad-20cf, U+2c60-2c7f,
      U+A720-A7FF;
  }
`
  • Use Global from @emotion/core:
import { Global, css } from '@emotion/core'

function App() {
  return (
   <div>
    <Global styles={
      css`
        @font-face {
          font-family: 'Patrick Hand SC';
          font-style: normal;
          font-weight: 400;
          src: local('Patrick Hand SC'),
            local('PatrickHandSC-Regular'),
            url(https://fonts.gstatic.com/s/patrickhandsc/v4/OYFWCgfCR-7uHIovjUZXsZ71Uis0Qeb9Gqo8IZV7ckE.woff2)
              format('woff2');
          unicode-range: U+0100-024f, U+1-1eff,
          U+20a0-20ab, U+20ad-20cf, U+2c60-2c7f,
          U+A720-A7FF;
        }
       `
      }
    />
    // Others
   </div>
 )
}

Upvotes: 2

Related Questions