DEV Community

csdj92
csdj92

Posted on

Using Font Awesome in React

Intro

While working on my latest side project I knew that I would need icons for my likes and comments component. In the past I had used Font Awesome for smaller projects and just stuck with the basic implementation.

<h1> Address Book </h1>
<i class="fas fa-address-book"></i>

<script src="https://kit.fontawesome.com/(yourKitCode).js" crossorigin="anonymous"></script>
Enter fullscreen mode Exit fullscreen mode

This lead to this issue Alt text of image

To some people this is okay but I enjoy no errors in my console.

Getting Started

To get started first we will need to install the following packages using either npm or yarn.

npm

  npm i --save @fortawesome/fontawesome-svg-core
  npm install --save @fortawesome/free-solid-svg-icons
  npm install --save @fortawesome/react-fontawesome
Enter fullscreen mode Exit fullscreen mode

yarn

  yarn add @fortawesome/fontawesome-svg-core
  yarn add @fortawesome/free-solid-svg-icons
  yarn add @fortawesome/react-fontawesome
Enter fullscreen mode Exit fullscreen mode

@fortawesome/fontawesome-svg-core is used as the base svg library, @fortawesome/free-solid-svg-icons refers to the free solid svg icons Library here and finally @fortawesome/react-fontawesome is the base library.

You can add additional styles with these

  npm install --save @fortawesome/free-brands-svg-icons
  npm install --save @fortawesome/free-regular-svg-icons
Enter fullscreen mode Exit fullscreen mode

Using Icons

Font Awesome gives two options to use when importing icons. The first is individual use and second is global use.
text

For individual use you would import like such

import React from 'react'
import { faHeart,faCommentDots,faShareSquare } from "@fortawesome/free-regular-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";

...
return (
<FontAwesomeIcon icon={faHeart} />
<FontAwesomeIcon icon={faCommentDots} /> 
<FontAwesomeIcon icon={faShareSquare} />
)
Enter fullscreen mode Exit fullscreen mode

For global usage add this to your app.js to initialize your app and library

import { library } from '@fortawesome/fontawesome-svg-core'
import { fab } from '@fortawesome/free-brands-svg-icons'
import { faCheckSquare, faCoffee } from '@fortawesome/free-solid-svg-icons' 

Enter fullscreen mode Exit fullscreen mode

Now my console is free of errors and I have nice looking icons.
text
For further instructions read Here.

Top comments (1)

Collapse
 
mrfufux profile image
Andrés Felipe

Thanks for sharing!