1

I have a list of items and need to render an image between every 10 items. Items should be rendered in a 2d grid, the image should appear in a new line.

it should be something like this: enter image description here

2
  • 1
    Have you tried anything? Commented Dec 8, 2018 at 19:12
  • I could list the items using map, I thought to check the index if it is divided by 10, we can add the image, but that didn't work. Commented Dec 8, 2018 at 19:17

2 Answers 2

2

This is one solution I think you can use:

<div id="container" style={{display: 'flex', flexDirection: 'row', flexWrap: 'wrap'}}>
{arrayList.map((listItem, index) => {
  const cardinalIndex = index + 1;
  const item = !(cardinalIndex % 10) ? (
    <React.Fragment>
      <div id="item" style={{flex: '1 1 25%'}}>
        {listItem}
      </div>
      <img style={{flex: '1 1 100%'}} src="" />
    </React.Fragment>
  ) : (
    <div id="item" style={{flex: '1 1 25%'}}>
      {listItem}
    </div>
  );
  return item;
})}

Sign up to request clarification or add additional context in comments.

12 Comments

@NadaGhanem Had the same idea, but I'm wondering how your code is different from mine
it is quite similar. Now, the image appears as an item, I wonder how to put it in a new line!
There is a couple problem with this code. 1. You render image instead of item and no between. 2. Item is the parameter of the map function and also redefined inside.
The above code replaces each 10th item by the image, which is not right, the item should be there!.
Yep! thank you @Peter I fixed it, also Nada the example also shows how to use flexbox in order to accomplish the layout on your picture
|
1
//itemList is your array

let temp = [];

while (itemList.length > 0) {
  temp.push(itemList.splice(0, 10));
}

let res = [];
temp.forEach(e => {
  res = [...res, ...e, 'new item here'];
});

//res is your output array with inserted elements

And here's working example: https://jsfiddle.net/tkr1d8vg/

1 Comment

Thanks, @h-des, I will test it with react, maybe there is an easier way to do it!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.