Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 />

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 */
]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading