Search code examples
reactjsfont-awesomereact-font-awesome

Set fontawesome icon from a variable - react


I'm building a react application:

"react": "^16.0.0",

with font awesome integrated.

"@fortawesome/fontawesome-svg-core": "^1.2.36",
"@fortawesome/free-brands-svg-icons": "^5.15.4",
"@fortawesome/free-solid-svg-icons": "^5.15.4",
"@fortawesome/react-fontawesome": "^0.1.15",

In a component, I want to set an icon from a const in another JSON file, but without variables it looks like this:

<FontAwesomeIcon icon={Brand_icons.faJava} size="6x" transform="shrink-6"/>

I've imported FontAwesomeIcon and other libraries like this:

import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import * as Brand_icons from '@fortawesome/free-brands-svg-icons';

This is my const and I want to set these icon names in a loop:

const skills = [
  "faJava",
  "faPython",
  "faJsSquare",
  "faReact",
  "faPhp"
];

and here is the loop I used to get these icon:

{skills.map((skill, index) => (
  <div>
    <FontAwesomeIcon icon={Brand_icons.faJava} size="6x" transform="shrink-6"/>
  </div>
))}

I want to set the value from the skill variable instead of faJava. How can I do that?


Solution

  • FontAwesome already exports fab from '@fortawesome/free-brands-svg-icons' which contains all the icons.

    You can change the import like this:

    import { fab as brandIcons } from '@fortawesome/free-brands-svg-icons';
    

    And change the render like this:

    {skills.map(skill => (
            <FontAwesomeIcon key={skill} icon={brandIcons[skill]} size="6x" transform="shrink-6" />
    ))}