Fix oversized icons from react-fontawesome

Problem

You are using react-fontawesome to render some Fontawesome icons in your app, and you notice that in an SSR build your icons get huge on page load, only to shrink back to their normal size a bit later. This is what it looks like:

Bug demonstration

And this is the code:

/** @jsx jsx */
import { jsx, Box } from "theme-ui";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faHeart } from "@fortawesome/free-solid-svg-icons";
import Layout from "@affectionatedoor/gatsby-theme-ui/src/components/Layout";

export default () => (
  <Layout>
    <Box
      sx={{
        position: "relative",
        minHeight: "70vh",
        bg: "mute",
        color: "accent",
      }}
    >
      <FontAwesomeIcon
        sx={{
          position: "absolute",
          top: "calc(50% - 20px)",
          left: "calc(50% - 20px)",
        }}
        icon={faHeart}
        size="2x"
      />
    </Box>
  </Layout>
);

Solution

To solve this—assuming you installed the @fortawesome/fontawesome-svg-core package—you’ll have to do 2 things:

  • Import the @fortawesome/fontawesome-svg-core/styles.css stylesheet before React loads. I’m using Gatsby, so I load the stylesheet in gatsby-browser.js:

    gatsby-browser.js
    import "@fortawesome/fontawesome-svg-core/styles.css";
  • Then prevent fontawesome from loading the CSS styles again:

    import { jsx, Box } from "theme-ui";
    import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
    import { faHeart } from "@fortawesome/free-solid-svg-icons";
    import Layout from "@affectionatedoor/gatsby-theme-ui/src/components/Layout";
    import { config } from "@fortawesome/fontawesome-svg-core";
    
    // You should do that in a Layout file or in `gatsby-browser.js`.
    config.autoAddCss = false;
    
    export default () => <Layout>{"Skipping content..."}</Layout>;

Now the icons are displayed in their correct size, as you can see in the following gif:

Bug resolved

Other things to read

Popular

Previous/Next