Question:
How to conditionally render different arrays in React?

Problem:

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>

    )}

  </>

);


Suggested blogs:

>Django Issue Solved: path searched will not match URL patterns

>Fix my form calling the wrong Django view error

>How is the value of the path column under the wagtailcore_page table populated?

>How to load static files using Nginx, Docker, and Django?

>How to tell Django "if anything in urlpatterns does not match the GET string?

>How can I browser to render links in streamed content in Django?

>Access the "model" attribute for a ListView in Django for template

>How to use a function to print S3 data to HTML using Django?



Ritu Singh

Ritu Singh

Submit
0 Answers