A full-stack hauman's space on the web.
The Best Way to Use Font Awesome in Next.js
The best way to use Font Awesome in Next.js is loading the icon sets globally and using TypeScript. Next.js will not include unused icons in the bundle, so there's no benefit to import icons individually. Here's how to set it up with minimal fluff.
Install the dependencies
You will want these four packages. The first two being most important, but the last two are basically necessary because they provide the common icons and social media brand icons that most people are likely looking for.
@fortawesome/fontawesome-svg-core
Manages your Font Awesome icons@fortawesome/react-fontawesome
React component@fortawesome/free-solid-svg-icons
Free solid icons@fortawesome/free-brands-svg-icons
Free solid brand icons
yarn add @fortawesome/fontawesome-svg-core @fortawesome/react-fontawesome @fortawesome/free-solid-svg-icons @fortawesome/free-brands-svg-icons
Install globally
In your _app.tsx
file, register icon sets with the library. You can import individual icons too, but you shouldn't bother because Next.js should remove the unused icons from the build if they are not used.
import { library } from '@fortawesome/fontawesome-svg-core'
import { fas } from '@fortawesome/free-solid-svg-icons'
import { fab } from '@fortawesome/free-brands-svg-icons'
library.add(fas, fab)
Use icons anywhere
Use the FontAwesomeIcon
component and add the icon
prop with a standard icon's name or specifying the icon set prefix and name in an array.
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
const Example = () => (<>
<FontAwesomeIcon icon={['fas', 'hamburger']}>
<FontAwesomeIcon icon="hamburger">
</>)
That's it! Now you can add Font Awesome icons to your Next.js projects quickly and easily.