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:
{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>
)}
</>
);