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?
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
IconPrefixfromfontawesome-svg-coreand set it as the type of the state. I'm going with that one:The second on is to go directly to the source of the type
IconPrefixand addstringas one of its types: - NOT RECOMMENDEDEDIT:
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,
IconPrefixwill 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:
That way no extra type need to be imported.