Using Font Awesome icons in Gatsby

July 11, 2020

The original landing page used icons and I wanted to replicate that on this website. I went down a couple of rabbit holes before finding the right solution.

Someone recommended installing react-icons but that didn’t work. I also looked at an article, Material Icon Font with Gatsby, that seemed to suggest that I could install the Material Icon “font” as a regular font, and get icons on my page. It would have been sweet if that would have worked, but it didn’t.

I decided to go with React Fontawesome. I installed the react-fontawesome library into my Gatsby project. I am using free icons for this project and I installed the free-regular-svg and free-solid-svg icons. The nice thing about doing it this way is that I get svg performance out of the box. And since my landing page is in JSX, it’s easy to include the icon like so:

import {FontAwesomeIcon} from '@fortawesome/react-fontawesome'
import {faUser, faEdit, faThumbsUp} from '@fortawesome/free-regular-svg-icons'
import {faListAlt, faCheckSquare} from '@fortawesome/free-regular-svg-icons'
import {faRedo, faShieldAlt, faGlobe, faAward} from
'@fortawesome/free-solid-svg-icons'
<FontAwesomeIcon icon={faUser} size="2x" color="#90CDF4"/>
<FontAwesomeIcon icon={faEdit} size="2x" color="#90CDF4"/>
<FontAwesomeIcon icon={faThumbsUp} size="2x" color="#90CDF4"/>
...

The only problem was finding the name of the React component which is passed as a prop to icon. From the Font Awesome v5.13.1 icons, I picked Free, Solid and Free, Regular icons.

For example, the “user” icon has html listed on top:

<i class="far fa-user"></i>

class far stands for font-awesome regular, and class fas would be font-awesome solid. I converted fa-user to pascal case faUser and used that as the name of the prop to pass to the FontAwesomeIcon React component. Note that faUser is imported from the @fortawesome/free-regular-svg icon package.

I am using just 9 icons on this website and opted to not create an icon library.

By now, I’ve gotten attuned to the fact that the Gatsby eco-system is a plugin based system, and looking for performance improvements I found and installed gatsby-plugin-fontawesome-css to get a more seamless experience with the font CSS included at compile time.

The power of MDX is that you can include React components in markdown, so just for kicks, here are 3 of the icons used on the landing page, faUser, faEdit and faThumbsUp:

I can space the icons using TailwindCSS in MDX:

<div className="flex flex-row mb-4">
<div className="mr-4">
<FontAwesomeIcon icon={faUser} size="2x" color="#90CDF4"/>
</div>
<div className="mr-4">
<FontAwesomeIcon icon={faEdit} size="2x" color="#90CDF4"/>
</div>
<div>
<FontAwesomeIcon icon={faThumbsUp} size="2x" color="#90CDF4"/>
</div>
</div>

Sweet!


tufan.io
Making it simple to create, manage & secure cloud applications.