user2840647
user2840647

Reputation: 1314

Programatically generating grid items with react-grid-layout

I am developing an application using Meteor and ReactJS. I am using the react-grid-layout component to create a grid of items.

The problem is that the position of each element needs to be specified manually. In my application, I am generating the grid items based on a Meteor Collection and I might not know how many items are in the collection.

Example

import React from "react";
import Item from "/ui/components/workspace/item.jsx";
import ReactGridLayout from 'react-grid-layout';

export default class WorkspaceGrid extends React.Component {
  componentDidMount() {

  }

  render() {
    let testCollection = [1,2,3,4,5,6,7,8,9,10]
    return (
      <ReactGridLayout isResizable={false} className="layout" cols={4} width={1200}>
        {testCollection.map((item, x) => 
            <Item key={x} _grid={{x: ?, y: ?, w: 1, h: 2}} />
        )}
      </ReactGridLayout>
    )
  }

}

In the above example, the grid should have 4 columns per row, but how would I specify the x and y values so that in testCollection items 1-4 are in row 1, 5-8 are in row 2, 9-10 are in row 3, and so on for however many items there are in the collection.

Thank you very much, help appreciated.

Upvotes: 4

Views: 5494

Answers (1)

Damien Leroux
Damien Leroux

Reputation: 11693

By default, react-grid-layout has parameter verticalCompact set to true, it means that if several items get the same y value, its will compact vertically. I think that you can write:

<Item key={x} _grid={{x: x%4, y: 0, w: 1, h: 2}} />

Several items will get the same y value but that is not a problem for react-grid-layout. x value will go from 0 to 3.

Upvotes: 5

Related Questions