How to Fix Font Awesome Icons Flashing Wrong Size in Gatsby

kayla

Kayla Sween

Posted on February 1, 2021

How to Fix Font Awesome Icons Flashing Wrong Size in Gatsby

Recently, I was working on a project with Font Awesome and Gatsby. I noticed that every time the page loaded after publishing the site, the icons would render huge for a split second. In my pre-React days, I remembered running into this annoying problem with Bootstrap 3 and Glyphicons. In that case, I knew it happened because I was importing the styles for the Glyphicons in the wrong order but wasn't sure how to fix that problem using React and Gatsby.

Bugs that only happen on page load or the first action of an element always seem to be the most frustrating ones to debug. Thankfully, the solution is relatively straightforward and should relieve your frustration in no time!

Why it happens

Since styles take a little extra time to download and get injected into the head, the icon is momentarily unstyled. Fabian Terh has a really great Medium article, "Fixing flashing huge Font Awesome icons on a Gatsby static site", which does a great job of explaining the why if you want a more thorough explanation.

How to fix it

In Gatsby, you'll add these lines of code to the beginning of your gatsby-browser.js. (It just so happens that this fix also works in Next.js if you stick this code into your _app.js file.)

const styles = require("@fortawesome/fontawesome-svg-core/styles.css")
const config = require("@fortawesome/fontawesome-svg-core")

config.autoAddCss = false

You could import the styles and config using ES6 syntax, like so:

import '@fortawesome/fontawesome-svg-core/styles.css'
import { config } from '@fortawesome/fontawesome-svg-core'

Let's break those down.

First, we're importing the Font Awesome styles manually and the config from the Font Awesome core library.

Then, we're setting config.autoAddCss to false so it doesn't automatically inject the CSS into the <head>.

That's it! I hope this helped someone because I know it'll certainly help me when I run into this problem again in the future!

💖 💪 🙅 🚩
kayla
Kayla Sween

Posted on February 1, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related