Fontawesome Icon not working as state value on React with TS

549 Views Asked by At

I am using an icon dynamically, so I would change the type of the icon with a state update, but I'm getting this error: Type 'string' is not assignable to type 'IconPrefix'.

Here is a sample of my code:

import  { useState } from 'react'

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

const Produto = () => {
   const [wishlistIcon, setWishlistIcon] = useState('far')
   
   return (
      <FontAwesomeIcon 
         icon={[wishlistIcon, 'heart']} size="2x"  
      />
   )
}

export default Produto

But if I pass the string directly as the icon value it works fine:

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

const Produto = () => {
   
   return (
      <FontAwesomeIcon 
         icon={['far', 'heart']} size="2x"  
      />
   )
}

export default Produto

Is there a way in which I could use this value as a state?

1

There are 1 best solutions below

0
Berg_Durden On

I found two solutions. I'm not sure if any of them is a good approach (it would be good if someone could clarify that for me), but they both work.

The first one is to import the IconPrefix from fontawesome-svg-core and set it as the type of the state. I'm going with that one:

import { IconPrefix } from '@fortawesome/fontawesome-svg-core'
const [wishlistIcon, setWishlistIcon] = useState<IconPrefix>('far')

The second on is to go directly to the source of the type IconPrefix and add string as one of its types: - NOT RECOMMENDED

export type IconPrefix = "fas" | "far" | "fal" | "fat" | "fad" | "fab" | "fak" | string ;

EDIT:

The second solution works, but it is not a good approach, since it will work in your machine, but once you (or anyone else) have to reinstall the project's dependencies, IconPrefix will be restored to its original values and your project will break.

The first approach is ok, but today (with more knowledge to understand what is happening) I would create a new type with the values I want to use, so TS will know that I'm following its rules and only using allowed values:

type Icon = 'fas' | 'far'
const [wishlistIcon, setWishlistIcon] = useState<Icon>('far')

That way no extra type need to be imported.