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" />
)}
</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
I believe that you forgot to import the icons globally.
Try importing as below:
import { library } from '@fortawesome/fontawesome-svg-core';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
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 { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import { faPlus, faMinus } from '@fortawesome/free-solid-svg-icons';
<button onClick={handleOpening} className="expandButton">
{!isOpen ? (
<FontAwesomeIcon icon={faPlus} />
) : (
<FontAwesomeIcon icon={faMinus} />
)}
</button>
Reference: How to set up Font Awesome in React