I have an object like this:
export const dataEstrenos = [
{
id: 1, product: "any product", title: "any title"
},
{
id: 2, product: "any product", title: "any title"
},
{
id: 3, product: "any product", title: "any title"
},
{
id: 4, product: "any product", title: "any title"
},
{
id: 5, product: "any product", title: "any title"
},
{
id: 6, product: "any product", title: "any title"
},
{
id: 7, product: "any product", title: "any title"
}
];
I want to display items in groups of four elements inside a container div, like this:
<div>
<div>Here data from first item</div>
<div>Here data from second item</div>
<div>Here data from third item</div>
<div>Here data from fourth item</div>
</div>
<div>
<div>Here data from fifth item</div>
<div>Here data from sixth item</div>
<div>Here data from seventh item</div>
</div>
…Items inside object may be any quantity, and the last container div may not have four items depending on how many items are left in the array/object (like the example above).
How can I achieve this in react? I am new to React so my attempts to achieve this are not worth showing here. Thank you!
2
Answers
I would first split the array in to sub arrays. If you have a favorite utility library it probably has a function for this, such as Lodash’s chunk, or Ramda’s splitEvery. Or you could write your own.
After that, map over the arrays like this:
Using Lodash library can provide you better performance in some case of data formatting
But if you want to write a vanilla react code, here’s a suggestion