Home > Enterprise >  How to map a string to a font awesome icon
How to map a string to a font awesome icon

Time:10-05

Hey folks I've been working through some mapping issues with font awesome and I am pretty close. I am mapping over a group of icons and returning an object that maps the string to a font awesome icon. I just don't know how to convert that string into the actual icon.

For example

import { faSave } from '@fortawesome/pro-light-svg-icons';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';

  icons.map((item) => {
    tmpArray.push(
      {
        [item.iconName] : faSave // this works but I need a unique icon for each string
        [item.iconName] : 'fa' upperFirst(camelCase(item.iconName)) // creates faSave string but needs to be an icon
      }
    )
  })

CodePudding user response:

Create a map of the names to the icons. This can be as simple as an object:

const iconsMap = { faSave } // using shorthand property initializer

// ...

icons.map((item) => {
  tmpArray.push(
    {
      [item.iconName] : iconsMap['fa' upperFirst(camelCase(item.iconName)) as keyof typeof iconsMap]
    }
  )
})

You'll then be able to get the correct icon for the name by indexing into it.

  • Related