Using Fontawesome with Nextjs


Using icons is common for building UI in web development. While my favorite icon library heroicons has a bunch of easy to use svg icons, Font Awesome free version provides loads more icons as a supplement. I am heavily using nextjs to build my frontend projects recently, unlike react or vue projects that have an index.html file we can import fontawesome as a stylesheet from cndjs. Nextjs doesn’t have a root template html file.

According their official doc about how to use fontawesome with react, we can follow the same way to use it in nextjs. But I prefer to import fontawesome as CSS-import as fontawesome under the hood is a CSS toolkit.

Install

We need first install fontawesome into our project via yarn (or npm):

1
yarn add @fortawesome/fontawesome-free

Import

For older nextjs projects, the _app.js file may not exist. We can manually create one under the pages folder.

1
2
3
4
5
// _app.js

import '@fortawesome/fontawesome-free/css/all.css';

// ...

Start using

Now we can use i tag inside any JSX components and specify icon inside className.

1
2
3
4
5
6
// react component
// ...
<i className="fas fa-camera" />
<i className="fas fa-camera fa-lg" />
<i className="fas fa-camera fa-3x" />
// ...

output will look like this:

fontawesome icons

What makes this even better is that we can seamlessly apply other CSS styles with those icons. For example, if I’d like to change colors of those icons with tailwind CSS:

1
2
3
4
5
6
// react component
// ...
<i className="fas fa-camera text-red-300" />
<i className="fas fa-camera fa-lg text-green-300" />
<i className="fas fa-camera fa-3x text-blue-300" />
// ...

We can easily get 3 icons with different colors: