0

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!

1 Answer 1

5

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>
)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.