-1

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?

Henrique Monteiro
  • 107
  • 1
  • 1
  • 9
  • I don't know if what you want is possible but you can pass the ```link.icon``` as a prop like this `````` no ? – VersifiXion Dec 05 '21 at 21:48
  • Does this answer your question? [Dynamically rendering component from string: ReactJS](https://stackoverflow.com/questions/48863490/dynamically-rendering-component-from-string-reactjs) – pilchard Dec 05 '21 at 21:49
  • also [How to render a react component from a string name](https://stackoverflow.com/questions/38823090/how-to-render-a-react-component-from-a-string-name) – pilchard Dec 05 '21 at 21:50
  • It should work setting it as a variable, a similar question was asked here: https://stackoverflow.com/questions/29875869/react-jsx-dynamic-component-name (note the PascalCase variable name on MyComponent) – andyd_28 Dec 05 '21 at 21:50

1 Answers1

1

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 */
]
Abbas Hussain
  • 1,277
  • 6
  • 14