0

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

1 Answer 1

5

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>;
Sign up to request clarification or add additional context in comments.

1 Comment

It worked! Thank you very much sir I learned new way of using component in array :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.