maximelian1986
maximelian1986

Reputation: 2452

Font Awesome icon in React

I was unable to get Font Awesome icon working when using string as value for icon parameter.

This working:

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

 <FontAwesomeIcon icon={faCoffee} />

However this does not:

import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';

<FontAwesomeIcon icon="coffee" />

And according to this documentation it should. But I am new to React so may be missing something.

Using javascript. Project created with react cli.

Package.json:

{
  "name": "test",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@fortawesome/fontawesome-svg-core": "^1.2.34",
    "@fortawesome/free-brands-svg-icons": "^5.15.2",
    "@fortawesome/free-regular-svg-icons": "^5.15.2",
    "@fortawesome/free-solid-svg-icons": "^5.15.2",
    "@fortawesome/react-fontawesome": "^0.1.14",
    "@testing-library/jest-dom": "^5.11.9",
    "@testing-library/react": "^11.2.3",
    "@testing-library/user-event": "^12.6.2",
    "font-awesome": "^4.7.0",
    "node-sass": "^4.14.1",
    "react": "^17.0.1",
    "react-dom": "^17.0.1",
    "react-metismenu": "^1.4.0",
    "react-router-dom": "^5.2.0",
    "react-scripts": "4.0.1",
    "rsuite": "^4.8.8",
    "web-vitals": "^0.2.4"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

By "not working" I mean that icon is not visible on the page and console have an error: "Could not find icon {prefix: "fas", iconName: "coffee"}"

Upvotes: 2

Views: 2751

Answers (1)

Riwen
Riwen

Reputation: 5190

You'll need to import library like this: import { library } from '@fortawesome/fontawesome-svg-core'

Then add the icon(s) you wish to use.

import { faCoffee } from '@fortawesome/free-solid-svg-icons'

library.add(faCoffee /*, faCheckSquare, etc*/)

After this, you should be able to use the icon as "coffee". If you are not adding the icons to the library, they will not be included in the bundle, hence the error.

Upvotes: 2

Related Questions