简体   繁体   中英

How do I insert a component within a MAP of other component in React?

I am creating a MAP to loop through an array of objects and display the data using a Card component. But within that MAP I need to insert another component called Banner after the second Card element from the loop, then continue the Card loop after the Banner. So it will be something like:

card[0] - card[1] - banner[0] - card[2] - card[3]

This is my map:

    { CardData.map((item) => (
     <Card key={item.id} title={item.title} image={item.image} url={item.url} desc={item.desc} />
    ))}

My banner component looks like this:

    <Banner title="Sample Title" image="../images/sample.jpg" />

How would I be able to achieve this? Any help will be extremely appreciated! Thank you very much in advanced!

You can conditionally return the banner right before the card only if the index is 2:

{
  CardData.map((item, index) => (
    <>
      {index == 2 && <Banner title="Sample Title" image="../images/sample.jpg" />}
      <Card key={item.id} title={item.title} image={item.image} url={item.url} desc={item.desc} />
    </>
  ))
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM