This article describes how to use font-awesome with a React Js project with Typescript. It's a bit different from React and Javascript approaches.
To use font awesome
To install font-awesome packages
npm i --save @fortawesome/fontawesome-svg-core
npm install --save @fortawesome/free-solid-svg-icons
npm install --save @fortawesome/react-fontawesome
npm install --save @fortawesome/free-brands-svg-icons
yarn add @fortawesome/fontawesome-svg-core
yarn add @fortawesome/free-solid-svg-icons
yarn add @fortawesome/react-fontawesome
yarn add @fortawesome/free-brands-svg-icons
The initialization is only necessary if you plan to use the font-awesome library globally in your application. That way you can avoid importing icon types in every component you use font-awesome. If you prefer importing them at the Component level you can skip to the next section. I initialize font-awesome in the index.tsx file since it is at a higher level than all the other components in the application.
import { faB, faCheckSquare, faCoffee, faDatabase, faHouseLaptop, faS, faWindowMaximize } from '@fortawesome/free-solid-svg-icons';
library.add(faB, faS, faHouseLaptop, faCheckSquare, faCoffee, faDatabase, faWindowMaximize)
Here, you will have to import all the icons you intend to use throughout the application.
If you have initialized the font-awesome library, you can use the FontAwesomeIcon component like below.
Note that I have imported
You need to have the faHouseLaptop import on the page.
To add an icon to a page, go to Font Awesome site and search for the icon you want. Let's say you want
This is how to make it work with Typescript.
The icon is
In font-awesome Typescript,
For the above align-right icon, you need to import and initialize
import { faS, faAlignRight } from '@fortawesome/free-solid-svg-icons';
library.add(faS, faAlignRight)
The IconProp type consists of IconPrefix and IconName. The valid Icon prefixes are
"fas" -> solid
"far" -> regular
"fal" -> light
"fat" -> thin
"fad" -> duotone
"fab" -> brand
Another example:
import { fab, faGithubSquare } from '@fortawesome/free-brands-svg-icons'
library.add(fab, faGithubSquare)
To add the font-awesome icons at the page level, simply use the icon name in-place of the IconProp type.