FortAwesome / react-fontawesome

Font Awesome React component
https://fontawesome.com
MIT License
3.67k stars 262 forks source link

Icon from variable #547

Open rwb196884 opened 1 year ago

rwb196884 commented 1 year ago

I want to insert an icon the name of which is stored in a variable.

Something like

let icon: string = 'user'; // It is impossible to use this.
...
<FontAwesomeIcon icon={['fas', icon]} />

At present this is impossible. None of the suggestions at https://stackoverflow.com/questions/69475336 work.

https://codesandbox.io/s/dreamy-wescoff-hyd1yo?file=/src/App.tsx

reinrl commented 7 months ago

@rwb196884 I got your example to work by changing the following:

import "./styles.css";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { fas } from "@fortawesome/free-solid-svg-icons";

// what you were trying to use...
const i: string = "circle-exclamation";
// ...but the string format needs to be like this to work
const icon: string = "faCircleExclamation";

export default function App() {
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
      <p>
        Icon {i} is <FontAwesomeIcon key={i} icon={fas[icon]} />
      </p>
    </div>
  );
}

In other words, it appears to be the naming of your icon that is giving you the trouble.

If instead you wanted to stick with your chosen naming, then you could do something like the following examples from the official documentation.

sunnyfeijen commented 5 months ago

@rwb196884 You should import the icon (or all icons) and add it to your library.

Codesandbox: https://codesandbox.io/p/sandbox/immutable-smoke-nypx79