DEV Community

Cover image for Typography in a CRA
Manav Misra
Manav Misra

Posted on

Typography in a CRA

Unsplash Photo by Alice Donovan Rouse

This post assumes familiarity with CRA (create-react-app).

Ease of Typography ✨

Recently, I discovered Typography.js. I love utilities like this because thinking about design sometimes is just too much for my feeble mind 🧠.

A powerful toolkit for building websites with beautiful design.

This means that we simply yarn add typography and then pick a theme (e.g. yarn add typography-theme-fairy-gates).

Then, in our app (maybe in 'index.js'):

import Typography from "typography";
import fairyGatesTheme from "typography-theme-fairy-gates";

const typography = new Typography(fairyGatesTheme);

typography.injectStyles();
Enter fullscreen mode Exit fullscreen mode

Upon removing πŸ”₯ all of the 'boilerplate CRA πŸ’©,' adding some basic text to render and then doing yarn start πŸ’¦ and then checking βœ”οΈ our app in the dev tools:

'script tags' for typography

With that, your typography already looks better...but depending on what fonts are on your system, you're probably looking πŸ‘€ at a 'fallback font.'

Actually Loading the 'Google Fonts' Stylesheet

This is b/c we are not actually linking to the font's 'Google fonts' stylesheet, and this is a bit tricky to 'inject' when using create-react-app due to it being a 'server' generated app.

We would need: yarn add react-typography...but since we are using CRA, it's not clear how to 'directly' inject this into our app.

The directions in the documentation are for 'non-CRA' apps where we are directly generating our entire HTML structure, as opposed to using the 'public' directory πŸ“.

Here's the fix:

  1. import { GoogleFont } from "react-typography";
  2. Inside of ReactDOM.render (in 'index.js' as per CRA):
  ReactDOM.render(
  <React.StrictMode>
    <App />

    {/* Add this element so we can see the 'link tag' generated in the dev tools markup. */}
    <GoogleFont typography={typography} />
  </React.StrictMode>,
  document.getElementById("root")
);
Enter fullscreen mode Exit fullscreen mode

Now, have a look again in 'dev tools' for your App and see something like this:

link tag to Google Fonts

Notice the link tag there.

Copy that and dump it into the <head> tag of 'public/index.html':

<link
      href="//fonts.googleapis.com/css?family=Work+Sans:600|Quattrocento+Sans:400,400i,700"
      rel="stylesheet"
      type="text/css"
    />
    <title>Expenses!</title>
  </head>
Enter fullscreen mode Exit fullscreen mode

You can now completely remove:

{/* Add this element so we can see the 'link tag' generated in the dev tools markup. */}
    <GoogleFont typography={typography} />
Enter fullscreen mode Exit fullscreen mode

You can also yarn remove react-typography

Top comments (0)