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

Conditionally render different arrays in React

I am trying to conditionally map through two different arrays in a reusable component. I can’t seem to get it to work. Obviously, I could just split them in two, but I’m trying to make the component reusable. Any ideas?

const fullStack = ["HTML", "CSS", "Javascript", "NodeJs", "React", "MongoDB", "Bootstrap"];
const  reactSkills=["React Query", "Redux", "Context API","Tailwind", "Custom Hooks","Supabase"];
               <div type={type}>
                    {type.map((skill)=> <li key={skill.id}>{skill}</li>)}  
                </div>

In a different component, I have the two different types attached to the reusable component.

            <EducationCard type="fullStack">
                <h1>Web Development Bootcamp - 2023</h1>
            </EducationCard>
            <EducationCard type="reactSkills">The Ultimate React Course</EducationCard>

I tried to conditionally render it like this:

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

{type === fullstack ? fullStack.map((skill)=> <li key={skill.id} >{skill}</li>) : reactSkills.map((skill)=> <li key={skill.id}>{skill}</li>)}

This didn’t work (and is also not very good code), so any other ideas would be appreciated.

>Solution :

Put both of the arrays in an object and refer to them by the appropriate key

const arrays = {
  fullStack: [
    /*...*/
  ],
  reactSkils: [
    /*...*/
  ],
};

const EducationCard = ({ type, children }) => (
  <>
    {children}
    {arrays[type] && (
      <ul>
        {arrays[type].map((skill, i) => (
          <li key={i}>{skill}</li>
        ))}
      </ul>
    )}
  </>
);
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