Reputation: 857
I have an array of objects and I want to display them in 6 Rows and 3 Cols Grid. I am using the following code.
const GridLayout = (props) => {
let layout = [];
let total_articles = props.articles.length;
let nRows = total_articles / 3;
let nCols = 3;
for (let i = 0; i < nRows; i++) {
layout.push(<div className="row">);
for (let j = 0; j < nCols && (i * nCols) + j < total_articles; j++) {
layout.push(
<div key={(i * nCols) + j} className="col-md-4 column">
<ArticleCard articleDetails={props.articles[(i * nCols) + j]}/>
</div>)
}
layout.push(</div>);
}
return (
<div id={"mainContent"} className="container">
{layout}
</div>
)
};
The first and last layout.push() are causing an issue and giving me a syntax error. If i remove them it works but just adds all the articles in one row, while I want it in 6 different rows.
I have a feeling I might have over complicated this and there must be a better way to accomplish the same thing, so would appreciate any help!
Upvotes: 0
Views: 9032
Reputation: 5797
Array.prototype.map()
is typically used to render()
lists in React.
As for gridding your layout; you might find CSS Grid
useful.
See below for a practical example.
const GridLayout = (props) => (
<div id="mainContent" className="container" style={{display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gridGap: '10px', gridAutoRows: 'minMax(100px, auto)'}}>
{this.props.articles.map((article) => (
<div>
<ArticleCard articleDetails={article}/>
</div>
))}
</div>
)
Upvotes: 5