Create new ul after every two elements with React

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>

Answer

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>
        );
      })}

Leave a Reply

Your email address will not be published. Required fields are marked *