skip to Main Content

I’m trying to add an icon to my react app that can conditionally be a plus or a minus. The icon is contained inside a circular button that works correctly aside from the fact that the icon it should contain is not shown.

Here is my code:


const [isOpen, setIsOpen] = useState(false)

const handleOpening = () => {
    setIsOpen((prev) => !prev)
}

<button onClick = {handleOpening} className = 'expandButton'>
    {!isOpen ? (
          <FontAwesomeIcon icon="fa-solid fa-plus" />
    ) : (
          <FontAwesomeIcon icon="fa-solid fa-minus" />-</div>
    )}
</button>

This is my package.json file and the dependencies it contains:

"dependencies": {
    "@fortawesome/fontawesome-svg-core": "^6.5.2",
    "@fortawesome/free-brands-svg-icons": "^6.5.2",
    "@fortawesome/free-regular-svg-icons": "^6.5.2",
    "@fortawesome/free-solid-svg-icons": "^6.5.2",
    "@fortawesome/react-fontawesome": "^0.2.0",

which I installed with this commands:

npm i --save @fortawesome/fontawesome-svg-core
npm i --save @fortawesome/free-solid-svg-icons
npm i --save @fortawesome/free-regular-svg-icons
npm i --save @fortawesome/free-brands-svg-icons
npm i --save @fortawesome/react-fontawesome@latest

2

Answers


  1. I believe that you forgot to import the icons globally.

    Try importing as below:

    import { library } from '@fortawesome/fontawesome-svg-core';
    import { fab } from '@fortawesome/free-brands-svg-icons';
    import { fas } from '@fortawesome/free-solid-svg-icons';
    import { far } from '@fortawesome/free-regular-svg-icons';
    
    export default App;
    
    library.add(fas);  // Import fa-solid icons only
    // library.add(fab, fas, far); // Import multiple fa styles icons
    

    Otherwise, you need to import icon individually:

    import { faPlus, faMinus } from '@fortawesome/free-solid-svg-icons';
    
    <button onClick={handleOpening} className="expandButton">
      {!isOpen ? (
        <FontAwesomeIcon icon={faPlus} />
      ) : (
        <FontAwesomeIcon icon={faMinus} />
      )}
    </button>
    

    Demo @ StackBlitz

    Reference: How to set up Font Awesome in React

    Login or Signup to reply.
  2. Did you include these lines, it’s required as per the documentation if you want to provide the value of icon= as string:

    import ReactDOM from 'react-dom'
    import { library } from '@fortawesome/fontawesome-svg-core'
    import { all } from '@awesome.me/kit-KIT_CODE/icons'
    
    library.add(...all)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search