Home > database >  Icons from react-icons with classes name instead of component
Icons from react-icons with classes name instead of component

Time:03-28

Is there a way in React Icons to specify my icons as a string, for example for the class name?

Currently I am using a React UI library which requires the names of the icons to be passed as their classes.

I know that you can use icons using react-icons as follows:

<FaArrowLeft/>

However, I would need the following icon name: "fa-arrow-left".

Is there any way I can get the class name instead of using the component?

CodePudding user response:

I haven't used React Icons specifically but I've gotten the result you are after by using bootstrap and font-awesome. Install bootstrap and font-awesome in you project.

yarn add bootstrap
yarn add font-awesome

Or

   npm install bootstrap
   npm install font-awesome

Import them (I import to my index.js file but where ever is the root of your app)

import 'bootstrap/dist/css/bootstrap.min.css';
import 'font-awesome/css/font-awesome.min.css';

Then you can use class names like

'fa fa-sm fa-eye'

for example to get a small eye icon.

CodePudding user response:

I am not sure which library you are using, but I'm assuming it's 'react-icons/fa'. It is possible to use it by string but after you import them all which might effect your bundle size by ~30MB extra which is not small size. Here is an example how to do it with custom component:

 import * as Icons from "react-icons/fa";
    
    const CustomFaIcon = ({ name }) => {
      const FaIcon = Icons[name];
      if (!FaIcon) return <p>Icon not found!</p>;
    
      return <FaIcon />;
    };
    
    export default function App() {
      return (
        <div className="App">
          <CustomFaIcon name="Your String" />
        </div>
      );
    }

I also suggest that you check out react-fontawesome library, you might end up with lower bundle size if you use it corrently, here you can find some examples how to do it: https://github.com/FortAwesome/react-fontawesome/blob/master/examples/create-react-app-typescript/src/App.tsx

  • Related