[1,2,3,4,5,6,7,...]
.<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>
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>
))
class App extends React.Component {
state = {
items: [...Array(20).keys()],
chunkLen: 3,
}
onClick = ({ target: { dataset: { change } } }) => {
this.setState(({ chunkLen }) => ({
chunkLen: Math.max(2, Math.min(9, chunkLen + +change)),
}));
}
render() {
const { items, chunkLen } = this.state;
const chunks = Array.from(
{ length: Math.ceil(items.length / chunkLen) },
(n, i) => items.slice(i * chunkLen, (i + 1) * chunkLen)
);
return (
<div>
<button data-change="-1" onClick={this.onClick}>-</button>
{chunkLen}
<button data-change="+1" onClick={this.onClick}>+</button>
<div>
{chunks.map(chunk => (
<div className="group">
{chunk.map(n => <div className="group-item">{n}</div>)}
</div>
))}
</div>
</div>
);
}
}