Home > Software design >  how to set react-icons in loop in reactjs
how to set react-icons in loop in reactjs

Time:01-15

hey everyone I'm in trouble here my code

I just want to use react icons in my project without doing other things

I just show icons in each data is rending

like this {<${e.contact.icons}/>} what I'm doing in code

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

// here is data for I want to show

const data = [
  {
    contact: [
      {
        title: "contact",
        subtitle: "get in touch",
icons:"FaBeer",

      },
{
        title: "contact",
        subtitle: "get in touch",
icons:"Fa500Px",
      },
{
        title: "contact",
        subtitle: "get in touch",
icons:"FaAccusoft",
      },
    ],
  },
];



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

export default contact;

{<${e.contact.icons}/>} this type method is not working it return outer like this in browser

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

here icons are not showing do should I do

CodePudding user response:

You can also use Parser() from html-react-parser. https://github.com/remarkablemark/html-react-parser

const parse = require('html-react-parser');
{parse(`<${e.contact.icons}/>`)};

CodePudding user response:

You cannot use strings to represent React Component Types, instead you can use the imported ComponentType itself.

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

// here is data for I want to show

const data = [
  {
    contact: [
      {
        title: "contact",
        subtitle: "get in touch",
        icons: FaBeer,
      },
      {
        title: "contact",
        subtitle: "get in touch",
        icons: Fa500Px,
      },
      {
        title: "contact",
        subtitle: "get in touch",
        icons: FaAccusoft,
      },
    ],
  },
];

const Contact = () => {
  return (
    <>
      {data.map((e, i) => {
        const Icon = e.contact.icons;
        return (
          <>
            <div className="text-area">
              <h1 className="title">{e.contact.title}</h1>
              <h2 className="subtitle">{e.contact.subtitle}</h2>
              <span><Icon /></span>
            </div>
          </>
        );
      })}
    </>
  );
};

export default Contact;

Note how the rendering of Icon changes as well

  •  Tags:  
  • Related