How to include a Font Awesome icon in React's render()

前端 未结 15 1670
刺人心
刺人心 2020-12-04 06:30

Whenever I try to use a Font Awesome icon in React\'s render(), it isn\'t displayed on the resulting web page although it works in normal HTML.

         


        
15条回答
  •  生来不讨喜
    2020-12-04 06:48

    After struggling with this for a while I came up with this procedure (based on Font Awesome's documentation here):

    As stated, you'll have to install fontawesome, react-fontawesome and fontawesome icons library:

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

    and then import everything to your React app:

    import { library } from '@fortawesome/fontawesome-svg-core'
    import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
    import { faStroopwafel } from '@fortawesome/free-solid-svg-icons'
    
    library.add(faStroopwafel)
    

    Here comes the tricky part:

    To change or add icons, you'll have to find the available icons in your node modules library, i.e.

    \node_modules\@fortawesome\free-solid-svg-icons  
    

    Each icon has two relevant files: .js and .d.ts, and the file name indicates the import phrase (pretty obvious...), so adding angry, gem and check-mark icons looks like this:

    import { faStroopwafel, faAngry, faGem, faCheckCircle } from '@fortawesome/free-solid-svg-icons'
    
    library.add(faStroopwafel, faAngry, faGem, faCheckCircle)
    

    To use the icons in your React js code, use:

    
    

    The icon name can be found in the relevant icon's .js file:

    e.g. for faCheckCircle look inside faCheckCircle.js for 'iconName' variable:

    ...
    var iconName = 'check-circle'; 
    ... 
    

    and the React code should look like this:

     
    

    Goodluck!

提交回复
热议问题