Font Awesome 6 (beta) and dynamic icon name in Next JS

Viewed 1581

I am developing a website with Next JS. This is the first time I use this language and I still have a lot to learn.

Now, I have a Pro subscription to Font Awesome and I am looking to use their component directly in my project, as described in their guides.

https://fontawesome.com/v6.0/docs/web/use-with/react/

https://fontawesome.com/v6.0/docs/web/use-with/react/add-icons

Basically, just using a component like this:

<FontAwesomeIcon icon={brands("google")} />

It works.

The problem, which I can't solve, is how to set the "google" value dynamically, in a previously initialized variable. I need that because this values are coming dynamically from a database.

If I try:

var example = "google";
<FontAwesomeIcon icon={brands(example)} />

Then I receive this error: "Only string literals are supported when referencing icons (use a string here instead)".

Anyone have any ideas?

2 Answers

The way you import your icons uses a babel macro. It means that the referenced icon must be known at build time. It just won't work, because Babel can't figure out what icon should be imported, it can only be done during runtime. That's why it tells you that only string literals are supported.

So you need to use the second method, explained in the docs. You have to have some kind of mapping between icon and the value from DB and then grab the relevant icon. Something like this:

// not sure about exact import
import { faGoogle } from '@fortawesome/free-brand-svg-icons';

// you'd put all valid values that can come from the backend here
const myIcons = {
  google: faGoogle
}

// ...

const example = 'google';
<FontAwesomeIcon icon={myIcons[example]} />

The other option is to use library.add, explained here and then do the same as above but instead of imported icon use a string, e.g. google: 'fa-brands fa-google' (again, not sure about exact value here).

Would the following work?

var example = ['fab', 'google'];

<FontAwesomeIcon icon={example} />

P.S. It is recommended to use the let or const keywords with ES6.

Related