reactjsnext.jsfont-awesome

FontAwesome Icons not working properly in react/next app


Solved - TLDR; Adding import '@fortawesome/fontawesome-svg-core/styles.css' to the _app.js / index.js file fixes the issue and FontAwesome works as intended. My issue was caused by npx-create-next-app including purgeCSS by default, which in turn stripped out the FontAwesome required styles.


I'm using FontAwesome in my Next app. I followed the React guide on the FA website and the icon SVG's are being output on the page. Problem is, none of the features work and they don't scale with font-size as they're meant to.

I don't want to hack it together by manually targeting the SVG's and adding size etc. as it's not ideal when it comes to responsiveness. i.e. it would be nice to have icons scale with accompanying text and the ability to add 'spinner', 'fixedWidth' etc.

Strangely, they have started working once or twice but then break again and I can't seem to reproduce.

// package.json
"dependencies": {
    "@fortawesome/react-fontawesome": "^0.1.14",
    "@fortawesome/fontawesome-svg-core": "^1.2.34",
    "@fortawesome/pro-regular-svg-icons": "^5.15.2",
  }
// _app.js
import { library } from '@fortawesome/fontawesome-svg-core'
import { faHeart } from '@fortawesome/pro-regular-svg-icons'
library.add( faHeart )
// header.js
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'

export default function Header() {

  return (
    <header>
      <FontAwesomeIcon icon={['far', 'heart']} spin />
    </header>
  )
}
// style.css
header {
 font-size: 20px; (does nothing to the icon)
}

svg {
 width: 20px; (works, but this shouldn't be required according to FA docs)
}

I've also tried individual use (importing icons into individual components, rather than utilising the library function) to the same effect. Like so:

// header.js
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import { faHeart } from '@fortawesome/pro-regular-svg-icons'

export default function Header() {

  return (
    <header>
      <FontAwesomeIcon icon={faHeart} spin />
    </header>
  )
}

Solution

  • Fixed it. The issue was purgeCSS which was added to the project when using npx-create-next-app. purgeCSS was purging the required FontAwesome styles.

    Explicitly importing the FontAwesome styles fixed the issue.

    Specifically, I added import '@fortawesome/fontawesome-svg-core/styles.css' to _app.js.