React - FontAwesome (Icon)

About

Fontawesome is a library of icon (free and paid). This section is talking about fontawesome integration into react.

For a totally free and easy to use library with the possibility to import your own svg, see React - Material UI - Icon

Style

When reading the documentation, you will find prefix that references a style (ie a collection of icons with the same design):

Prefix Style / Link Pricing
fab font awesome brands icons free
fas font awesome solid icons free
far font awesome regular style somewhat free
fal font awesome light style pro
fad font awesome [duotone style pro

Additional:

Installation

# the core
yarn add @fortawesome/fontawesome-svg-core
# the react integration
yarn add @fortawesome/react-fontawesome
# the style
yarn add @fortawesome/free-solid-svg-icons
yarn add @fortawesome/free-regular-svg-icons
yarn add @fortawesome/free-brands-svg-icons

Syntax

FontAwesomeIcon component

Icon Prop

The basic FontAwesomeIcon can be called with three differents icon prop ways.

<FontAwesomeIcon icon='{faCoffee}' />
<FontAwesomeIcon icon='coffee' />
<FontAwesomeIcon icon={['fas', 'coffee']} />

The icon prop value can be:

  • a icon object, like {faCoffee}.
  • a string object, like coffee
  • an array {[“fas”, “coffee”]} where:
    • the first element is a prefix,
    • and the second element is the icon name:

Other Properties

Properties are called features

Example: Size where the icon size is relative to the current font-size.

<FontAwesomeIcon icon="spinner" size="xs" />

Import Usage

Explicit Import

Works out of the box with Javascript and typescript

import ReactDOM from 'react-dom'
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import { faCoffee } from '@fortawesome/free-solid-svg-icons'

const element = <FontAwesomeIcon icon={faCoffee} />

Implicit Import With Library

A library should created before an implicit import (where the icon are looked up by name).

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

library.add(fab, faCheckSquare, faCoffee)

Usage:

  • with javascript (ie without typescript)
// All fab icon are available, then you can reference them directly
<FontAwesomeIcon icon={['fab', 'apple']} />

// The faCheckSquare, faCoffee where added, then you can reference them
// and the fas prefix (for Font Awesome Solid) is being inferred as the default. 
<FontAwesomeIcon icon="coffee" />
<FontAwesomeIcon icon="check-square" />
  • with typescript
import {
  IconLookup,
  IconDefinition,
  findIconDefinition
} from '@fortawesome/fontawesome-svg-core'

const coffeeLookup: IconLookup = { prefix: 'fas', iconName: 'coffee' }
const coffeeIconDefinition: IconDefinition = findIconDefinition(coffeeLookup)

// then object syntax
<FontAwesomeIcon icon={coffeeIconDefinition} />

Doc


Powered by ComboStrap