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.
-
1Have you tried anything?kind user– kind user2018-12-08 19:12:04 +00:00Commented 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.Nada Ghanem– Nada Ghanem2018-12-08 19:17:42 +00:00Commented Dec 8, 2018 at 19:17
Add a comment
|
2 Answers
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;
})}
12 Comments
Benjamín Vázquez
@NadaGhanem Had the same idea, but I'm wondering how your code is different from mine
Nada Ghanem
it is quite similar. Now, the image appears as an item, I wonder how to put it in a new line!
Peter Ambruzs
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.
Nada Ghanem
The above code replaces each 10th item by the image, which is not right, the item should be there!.
Benjamín Vázquez
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
|
//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
Nada Ghanem
Thanks, @h-des, I will test it with react, maybe there is an easier way to do it!
