Answer the question
In order to leave comments, you need to log in
How to split an array into divs in react?
An array comes in: [1,2,3,4,5,6,7]...
It is necessary that the output be like this:
<div>
<div>1</div>
<div>2</div>
<div>3</div>
</div>
<div>
<div>4</div>
<div>5</div>
<div>6</div>
</div>
<div>
<div>7</div>
</div>
Answer the question
In order to leave comments, you need to log in
Please, here's to you via reduce:
const chunks = [1,2,3,4,5,6,7].reduce((chunks, value, index) => {
const chunkIndex = Math.floor(index / 3);
if (!chunks[chunkIndex]) {
chunks[chunkIndex] = [];
}
chunks[chunkIndex].push(value);
return chunks;
}, []);
return chunks.map((chunk) => (
<div key={chunk.join(`-`)}>
{chunk.map((value) => (
<div key={value}>
{value}
</div>
))}
</div>
))
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question