Search code examples
javascriptarraysreactjstypescriptreact-component

How to render a component which name is given by an array mapping?


I have an array of data, like so:

export const links = [
  {
    name: 'Facebook',
    url: 'https://facebook.com',
    icon: 'SiFacebook',
  },
  /* ... rest of it */
]

Then, for each of these icon names, i have a component (which is actually an icon using React Icons, for example, i would render:

<SiFacebook />

So, after i map it on my page, i need to render something like this:

                  {links.map((link: any, index: any) => (
                      
                    <li
                      key={index}
                      className="w-60 rounded-md bg-neutral-focus grid grid-cols-1 p-3 mx-2"
                    >
                      {React.createElement(`${link.icon}` ,{})}
                      <a
                        href={link.url}
                        target="_blank"
                        rel="_noreferrer"
                        className="text-sm font-bold"
                      >
                        {link.name}
                      </a>
                    </li>
                  ))}

So i need to render each link.icon as a component. I tried using React.createElement but it didn't work. Other ways also didn't work. What am i doing wrong?


Solution

  • that's not possible because you also need to import the icon according to react icon docs --> https://react-icons.github.io/react-icons/ where you are trying to render, the other and a better way around is to send icon as a component from the array like this

    import { FaBeer } from 'react-icons/fa';
    
    export const links = [
      {
        name: 'Facebook',
        url: 'https://facebook.com',
        icon: <FaBeer />,
      },
      /* ... rest of it */
    ]