reactjsreact-icons

How to use "react-icons" in loop (Map method) in ReactJS 😅


I'm using React-icons in my ReactJS project and I just wanted to loop (by Map method) the specific icons in each JSX field when data is render.

In other word, I want this{`<${e.contact.icons}/>`}in JSX code. Here is my code section:-

Here is, I import some icons for React icons.

import { FaBeer, Fa500Px, FeAccusoft } from "react-icons/fa";

Here is a data array which I want to render in JSX.

const data = [
  {
    contact: [
      {
        title: 'contact',
        icons: 'FaBeer',
      },
      {
        title: 'contact',
        icons: 'Fa500Px',
      },
      {
        title: 'contact',
        icons: 'FaAccusoft',
      },
    ],
  },
]

And this is my component in down below. Which I'm using icons. You get little idea what I want to do.

const contact = () => {
  return (
    <>
      {data.map((e, i) => {
        return (
          <>
            <div className="text-area">
              <span> {`<${e.contact.icons}/>`} </span>
            </div>
          </>
        );
      })}
    </>
  );
};

export default contact;

I'm trying to use like this{`<${e.contact.icons}/>`}, but is not working. When I see in browser. It's look like this.

<FaBeer/>
<Fa500Px/>
<FaAccusoft/>

It's just return like a text, but I want to get icons.

Any suggestion ?

Solution

  • Well, the option of importing FaIcon-s and putting them into "data" array looks pretty nice:

    import { FaBeer, Fa500Px, FaAccusoft } from "react-icons/fa";
    
    const data = [
      {
        contact: [
          {
            title: "contact",
            subtitle: "get in touch",
            icons: FaBeer,
          },
    ...
    

    On the other hand possibility of generating components "dynamically" by their string name could be still implemented.

    Firstly, I find usefull following article: React / JSX Dynamic Component Name

    Next, I've created a new FaIconDynamic component:

    import {
        AiFillAccountBook,
        AiFillAlert,
        AiFillAlipayCircle,
        AiFillAndroid,
    } from 'react-icons/ai';
    
    export const FaIconDynamic = ({ type }) => {
        const FaIcon = components[type];
        return <FaIcon></FaIcon>;
    };
    
    const components = {
        AiFillAccountBook,
        AiFillAlert,
        AiFillAlipayCircle,
        AiFillAndroid,
    };
    

    And then that's pretty easy to generate any registered above fa-icon, f.e.:

    function App() {
        return (
            <>
                <FaIconDynamic type={'AiFillAccountBook'} />
                <FaIconDynamic type={'AiFillAlert'} />
                <FaIconDynamic type={'AiFillAlipayCircle'} />
                <FaIconDynamic type={'AiFillAndroid'} />
            </>
        );
    }
    

    Of course, both approaches have their pros and cons and could be more benefitial in some situations over each other