1
votes

I am using FontawesomeIcon in a react js project and the names of the icons are coming from the database. I want to import the icons coming from the database from @fortawesome/free-solid-svg-icons dynamically

import React, { Component } from "react";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import {faImage} from "@fortawesome/free-solid-svg-icons";

export class Features extends Component {
  render() {
    return (
      <div id="features" className="text-center">
        <div className="container-fluid">
          <div className="features-listing">
            {this.props.data.map((item, index) => (
              <div key={`${index}`}>
                {" "}
                <FontAwesomeIcon icon={item.icon} />
                <h3>{item.title}</h3>
              </div>
            ))}
          </div>
        </div>
      </div>
    );
  }
}

export default Features;
3

3 Answers

3
votes

In App.js, you can import all the icons, as seen in this post, like this:

import {library} from '@fortawesome/fontawesome-svg-core';
import * as Icons from '@fortawesome/free-solid-svg-icons';

const iconList = Object.keys(Icons)
  .filter((key) => key !== 'fas' && key !== 'prefix')
  .map((icon) => Icons[icon]);

library.add(...iconList);

Then, inside components, only import the FontAwesomeIcon and use them:

import {FontAwesomeIcon} from '@fortawesome/react-fontawesome';

<FontAwesomeIcon icon="times" />
2
votes

There is actually a better way without having to iterate all icons (@Andrei Rosu's solution), you can export the whole brand and solid packages:

import { library } from '@fortawesome/fontawesome-svg-core'
import { fab } from '@fortawesome/free-brands-svg-icons'
import { fas } from '@fortawesome/free-solid-svg-icons'

// This exports the whole icon packs for Brand and Solid.
library.add(fab, fas)

and to use them:

import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'

<FontAwesomeIcon icon={['fab', 'apple']} /> // any icon from Brand.
<FontAwesomeIcon icon={['fas', 'coffee']} /> // any icon from Solid.
0
votes

Just simply add the Fontawesome CDN to your HTML Header and use any icon you want,

it would be something like this in react:

    <i className={object.ico}><i/>

Object.ico should be a string containing the icon name like far fa-xyz