Home > Mobile >  How to add a className to a reactjs component that is inside an array?
How to add a className to a reactjs component that is inside an array?

Time:08-14

I have an array that contains objects containing icon component and titles like this :

 const skills = [
    { icon: <FaHtml5 className="skill-icon" />, title: "HTML5" },
    { icon: <FaCss3 className="skill-icon" />, title: "CSS3" },
    { icon: <SiJavascript className="skill-icon" />, title: "JavaScript" },
    { icon: <FaReact className="skill-icon" />, title: "ReactJS" },
    { icon: <SiBootstrap className="skill-icon" />, title: "Bootstrap" },

  ];

I have to write className="skill-icon" to every component... I tried this way of adding className but this didn't work:

skills.map((add_class) => {
    add_class.icon.add.classList("myClass");
    console.log(add_class);
  });

Should we have to write className='skill-icon' inside that array like I'm doing or is there any other way to iterate over all the component and add className ?

My HTML looks like this :


      <section className="skill-card-section">
        {skills.map((skill) => {
          //iterating over all the skills from that skills array
          return (
            <section className="skill-card" key={skill.title}>
              {skill.icon}
              <p className="skill-title">{skill.title}</p>
            </section>
          );
        })}
      </section>

CodePudding user response:

Instead of creating a React.Node (by calling <Component/> which is a synthetic sugar for React.createElement) in your skills array, you can assign the component itself.

const skills = [
  { iconComponent: FaHtml5, title: "HTML5" },
  { iconComponent: FaCss3, title: "CSS3" },
  { iconComponent: SiJavascript, title: "JavaScript" },
  { iconComponent: FaReact, title: "ReactJS" },
  { iconComponent: SiBootstrap, title: "Bootstrap" },
];

<section className="skill-card-section">
  {skills.map((skill) => {
    const Component = skill.iconComponent;
    return (
      <section className="skill-card" key={skill.title}>
        <Component className="skill-icon" />
        <p className="skill-title">{skill.title}</p>
      </section>
    );
  })}
</section>;
  • Related