K
K
Kirill2021-02-03 14:49:00
JavaScript
Kirill, 2021-02-03 14:49:00

How to loop through slides and cards inside them?

https://codesandbox.io/s/mystifying-proskuriakova-huimi

There is an object with data for cards, 6 cards and 2 slides. It is necessary to go through all this in a loop so that 3 cards with filled data from the object are inserted into each slide, and if you add 3 more cards to the object, then they will be displayed correctly. Tell me how can this be done?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2021-02-03
@Lirrr

Two things are needed.
The first is a function that will cut the array into pieces:

const chunks = (arr, chunkSize) => Array.from(
  { length: Math.ceil(items.length / chunkSize) },
  (n, i) => items.slice(i * chunkSize, (i + 1) * chunkSize)
);

The second is the card component:
const Card = props => (
  <div className="style-review__slide-row">
    <a className="style-card style-review__style-card" href="#">
      <div className="style-card__overlay">
        <div className="style-card__title">{props.title}</div>
        <div className="style-card__category">
          {props.category}
        </div>
      </div>
    </a>
  </div>
);

After that, all that remains is to get an array consisting of data arrays for individual cards: And render it:
const chunkedItems = chunks(items, 3);
<Swiper>
  {chunkedItems.map(cardItems => (
    <SwiperSlide className="swiper-slide style-review__slide">
      {cardItems.map(n => <Card {...n} />)}
    </SwiperSlide>
  ))}
</Swiper>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question