Font awesome react typescript

How to use font awesome in React and Typescript

This article describes how to use font-awesome with a React Js project with Typescript. It’s a bit different from React and Javascript approaches.

  1. Install font-awesome npm packages
  2. Init the font-awesome library in index.js or index.tsx
  3. Use the icons with the FontAwesome component

To install font-awesome packages
using NPM:

npm i --save @fortawesome/fontawesome-svg-core npm install --save @fortawesome/free-solid-svg-icons npm install --save @fortawesome/react-fontawesome npm install --save @fortawesome/free-brands-svg-icons
yarn add @fortawesome/fontawesome-svg-core yarn add @fortawesome/free-solid-svg-icons yarn add @fortawesome/react-fontawesome yarn add @fortawesome/free-brands-svg-icons

Initializing the font-awesome library

The initialization is only necessary if you plan to use the font-awesome library globally in your application. That way you can avoid importing icon types in every component you use font-awesome. If you prefer importing them at the Component level you can skip to the next section. I initialize font-awesome in the index.tsx file since it is at a higher level than all the other components in the application.

import < faB, faCheckSquare, faCoffee, faDatabase, faHouseLaptop, faS, faWindowMaximize >from '@fortawesome/free-solid-svg-icons'; library.add(faB, faS, faHouseLaptop, faCheckSquare, faCoffee, faDatabase, faWindowMaximize)

Here, you will have to import all the icons you intend to use throughout the application.

Читайте также:  Можно ли создать объект интерфейса java

How to use the icons in the React Components?

If you have initialized the font-awesome library, you can use the FontAwesomeIcon component like below.

Note that I have imported fas and house-laptop as faS and faHouseLaptop in index.tsx file. If you decide to import the icons at the page level, the FontAwesomeIcon component will like below.

You need to have the faHouseLaptop import on the page.

import < faHouseLaptop >from «@fortawesome/free-solid-svg-icons»;

How to add a specific font-awesome icon in React Typescript?

To add an icon to a page, go to Font Awesome site and search for the icon you want. Let’s say you want on your page. But since you use Typescript, you will get a type error.

This is how to make it work with Typescript.

The icon is fa-solid fa-align-right .
In font-awesome Typescript, fa-solid is represented by fas and fa-align-right by align-right . The icon property type is IconProp instead of a string. Therefore, the correct usage is:
/>

For the above align-right icon, you need to import and initialize align-right as below.

import < faS, faAlignRight >from '@fortawesome/free-solid-svg-icons'; library.add(faS, faAlignRight)

The IconProp type consists of IconPrefix and IconName. The valid Icon prefixes are

"fas" -> solid "far" -> regular "fal" -> light "fat" -> thin "fad" -> duotone "fab" -> brand
import < fab, faGithubSquare >from '@fortawesome/free-brands-svg-icons' library.add(fab, faGithubSquare)

How to add font-awesome icons in React Typescript without initializing?

To add the font-awesome icons at the page level, simply use the icon name in-place of the IconProp type./>

Источник

React

Font Awesome now has an official React component that’s available for a friction-less way to use our icons in your React applications.

Remove ads with a Pro plan!

A subscription to a Pro-level plan will remove all third-party advertisements on fontawesome.com.

And of course Pro-level plans come with…

Get Font Awesome Pro for only $99/yr

Before You Get Started

    want to use React and not React Native (which is a different react-native-fontawesome

To get started you’ll need to install the following packages into your project using a package manager like npm

(opens new window) . Here are examples that install everything you need and our solid style of icons using each respective package manager.

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

(opens new window) between —save and —save-dev . Yarn also lets you use —dev to save as a development dependency.

If you want to use additional styles of icons, you’ll need to install them as well. Here’s an example of how to add our brand icons and the free set of our regular style icons via npm

npm i --save @fortawesome/pro-solid-svg-icons npm i --save @fortawesome/pro-regular-svg-icons npm i --save @fortawesome/pro-light-svg-icons npm i --save @fortawesome/pro-duotone-svg-icons 
yarn add @fortawesome/pro-solid-svg-icons yarn add @fortawesome/pro-regular-svg-icons yarn add @fortawesome/pro-light-svg-icons yarn add @fortawesome/pro-duotone-svg-icons 

In order to use Pro icons, you’ll need to pass the type of icon you want to use into the icon prop of the component. Read on for more detailed instructions about usage:

 // Light: FontAwesomeIcon icon=["fal", "coffee"]> /> // Regular: FontAwesomeIcon icon=["far", "coffee"]> /> // Solid FontAwesomeIcon icon=["fas", "coffee"]> /> // . or, omit as FontAwesome defaults to solid, so no need to prefix: FontAwesomeIcon icon="coffee" /> // Brand: FontAwesomeIcon icon=["fab", "github"]> /> 

This package, under the hood, uses SVG with JS and the @fortawesome/fontawesome-svg-core library. This implementation differs drastically from the classic Web Font-based one in Font Awesome 4 and earlier. If you want to know the details, read up on fontwesome-svg-core. If you’re coming from Version 4, we also recommend learning more about upgrading to Font Awesome 5 in general.

Remove ads with a Pro plan!

A subscription to a Pro-level plan will remove all third-party advertisements on fontawesome.com.

And of course Pro-level plans come with…

Get Font Awesome Pro for only $99/yr

Once you’ve installed all the packages you need for your project, there are two ways you can use Font Awesome 5 with React. Here’s a summary of both options as well as their benefits and possible drawbacks.

Option Benefits Drawbacks
Individual Use Allows icons to be subsetted, optimizing your final bundle. Only the icons you import are included in the bundle. Explicitly importing icons into each of many components in your project can become tedious.
Global Use Individually import icons just once in an init module — there’s no need to import the icons into each component once they’ve been added to the library. You may be including files that won’t be used and could impact performance.

Using Icons via Individual Use

Again, with this method, you’ll need to explicitly import icons into each component. Here’s a simple example.

 import ReactDOM from 'react-dom' import  FontAwesomeIcon > from '@fortawesome/react-fontawesome' import  faCoffee > from '@fortawesome/free-solid-svg-icons' const element = FontAwesomeIcon icon=faCoffee> /> ReactDOM.render(element, document.body) 

Notice that the faCoffee icon is imported from @fortawesome/free-solid-svg-icons as an object and then provided to the icon prop as an object.

Also, for the above example, we’re referencing the @fortawesome/free-solid-svg-icons module, so make sure you’ve already installed that package in your project.

Using Icons via Global Use

You probably want to use our icons in more than one component in your project, right? Importing icons into each of your project’s components can be really tedious and prone to display errors — especially over time.

Instead, you can add them once in your React application and reference them in any component. We recommend importing them via a «library» in the initializing module of your React application. Here’s an example.

Let’s say you have a React Application, «Coffee Checker», that alerts users when recently brewed coffee has been sitting around too long and freshness is compromised.

We use Coffee Checker’s App.js to initialize our app and library. Our app’s UI wants to use two individual icons, faCheckSquare and faCoffee . We also add all of the brands in @fortawesome/free-brands-svg-icons to build the showcase of the big companies that fictitiously use «Coffee Checker» over time.

 import ReactDOM from 'react-dom' import  library > from '@fortawesome/fontawesome-svg-core' import  fab > from '@fortawesome/free-brands-svg-icons' import  faCheckSquare, faCoffee > from '@fortawesome/free-solid-svg-icons' library.add(fab, faCheckSquare, faCoffee) 

In our call to library.add() you’re passing:

  • fab : which represents all of the brand icons in @fortawesome/free-brands-svg-icons . So any of the brand icons in that package may be referenced by icon name as a string anywhere else in our app. For example: «apple» , «microsoft» , or «google» .
  • faCheckSquare and faCoffee : Adding each of these icons individually allows us to refer to them throughout our app by their icon string names, «check-square» and «coffee» , respectively.

Our application also has React components, Beverage and Showcase . After initializing the above library, you don’t have to re-import icons into each of them. We import the FontAwesomeIcon component, and when used, you supply the icon prop an icon name as a string. Here’s how that looks in our functional component, Beverage.js :

 import React from 'react' import  FontAwesomeIcon > from '@fortawesome/react-fontawesome' export const Beverage = () => ( div> FontAwesomeIcon icon="check-square" /> Your FontAwesomeIcon icon="coffee" /> is hot and ready! div> ) 

Heads Up: Solid is the Default Style

There’s one another piece of magic that’s happening in the background when providing icon names as strings like this: the fas prefix (for Font Awesome Solid) is being inferred as the default.

And here’s the Showcase.js component:

 import React from 'react' import  FontAwesomeIcon > from '@fortawesome/react-fontawesome' export const Showcase = () => ( div> FontAwesomeIcon icon=['fab', 'apple']> /> FontAwesomeIcon icon=['fab', 'microsoft']> /> FontAwesomeIcon icon=['fab', 'google']> /> FontAwesomeIcon icon="check-square" /> With Coffee Checked, these companies always know their coffee is hot and ready! div> ) 
  • We used the «check-square» icon name again in this component, though you didn’t have to explicitly import it into this component thanks to the previous import and library addition in our App.js .
  • The «check-square» icon is getting a default prefix of fas here too, which is what you want, because that icon also lives in the @fortawesome/free-solid-svg-icons package.
  • We used the «apple» , «microsoft» , and «google» brand icons, which were never explicitly individually imported, but they’re available to us by name as strings because all brand icons were added to our library in App.js , and fab includes all of those icons.
  • We added the Brands-specific fab style prefix to reference those 3 brand icons.

Remove ads with a Pro plan!

A subscription to a Pro-level plan will remove all third-party advertisements on fontawesome.com.

And of course Pro-level plans come with…

Get Font Awesome Pro for only $99/yr

As our examples above show, the syntax to reference an icon in the above components is different than our traditional HTML-based syntax. These are all valid ways to define the icon prop:

 FontAwesomeIcon icon="coffee" /> FontAwesomeIcon icon=['fas', 'coffee']> /> FontAwesomeIcon icon=['far', 'coffee']> /> FontAwesomeIcon icon=faCoffee> /> 

The icon prop expects a single object:

  • It could be an icon object, like .
  • It could a string object, like «coffee» . (The curly braces around a string object supplied to a prop are optional, so they were omitted.)
  • Or it could be an Array of strings, where the first element is a style prefix, and the second element is the icon name:

More About Styles + Prefixes

We added more styles in Font Awesome 5 and are using prefixes to call specific ones when rendering icons. Check out our complete list of styles to see what’s available in Font Awesome Free and Pro.

All of the style toolkit features available for general web use are also available in the official Font Awesome React component. Note, however, that the syntax is different from our general web-use documentation.

We’re Using Shortcuts Below

In the following code snippets, you’ll use the shortcut notation for the icons—referencing the icons by their names as strings. But remember, that option is only valid after you’ve either explicitly imported and added those icons to the library, or externally loaded an icon bundle. See the sections above for the details.

 FontAwesomeIcon icon="coffee" size="xs" /> FontAwesomeIcon icon="coffee" size="lg" /> FontAwesomeIcon icon="coffee" size="6x" /> 

Note that icon size can be controlled with the CSS font-size attribute, and FontAwesomeIcon ‘s size prop determines icon size relative to the current font-size .

 FontAwesomeIcon icon="coffee" fixedWidth /> 

Источник

Оцените статью