Create new ul after every two elements with React

Viewed 108

I am making a food ordering website. On the frontpage I get all food images from my database and then as you see on the code below, I use docs.map to render all the images. The problem is, I want to have a maximum of two images inside the ul tag, but right now all the images are put into one single ul. So if there was 6 images, there would also be 3 ul.

<div className="cards__wrapper">
          <ul className="cards__items">
            {docs &&
              docs.map((doc) => (
                <CardItem
                  src={doc.url}
                  key={doc.id}
                  text={doc.imageText}
                  price={doc.price}
                  id={doc.id}
                ></CardItem>
              ))}
          </ul>
        </div>

2 Answers

You can split the array to the required chunks and render the data based on that. I have made a example for that. you can check this

Split Function

 var chunks = function (array, size = 2) {
    var results = [];
    while (array.length) {
      results.push(array.splice(0, size));
    }
    return results;
  };

 const data = chunks(lists, 2);

Render :

   {data.map((childs, index) => {
        return (
          <ul>
            {childs.map((c, cindex) => {
              return <li>{c + index + cindex}</li>;
            })}
          </ul>
        );
      })}
  const docs = [1, 2, 3, 4, 5, 6, 7];
  const ulArr = [];

  docs.forEach((item, i, arr) => {
    if (i % 2 !== 0) {
      ulArr.push([arr[i - 1], item]); //add 2 elements ib Array
    }

    if (i == arr.length - 1) {
      ulArr.push([item]) //add last element in last array
    }
  })

You need to go through ulArr through the map and return one map with LI elements

Related