[Fixed]-How can I achieve the following grid output in React/JSX?


Remember, JSX isn’t a templating language–it is directly transplited to JavaScript function calls. So, when you’re writing JSX, unlike writing templates in Django/Handlebars/etc., you have the full power of JavaScript at your disposal. For that reason, it’s usually best to think about shaping your data so you can iterate it easily and create the DOM structure you want. Methods like map and reduce are your friends here.

For example, say you wanted to render these eight “items” in such a layout:

var items = ["one", "two", "three", "four", "five", "six", "seven", "eight"];

What you really want to do is render a row for every four objects, and then a div for each object in that row. So let’s create a component that splits the data in just such a fashion.

var PinterestLayout = React.createClass({
  render: function() {
    // Here we'll just use Lo-dash's `chunk` method to split our data
    // into the right sized groups.
    var groups = _.chunk(this.props.items, 4);
    // Now `groups` is an array of arrays that looks like:
    // [ ["one", "two", "three", "four"],
    //   ["five", "six", "seven", "eight"] ]
    // Let's render a row for each group.
    return <div>{groups.map(this.renderRow)}</div>;

  renderRow: function(row) {
    // Now `row` is just an array of four items,
    // which we can render just how you'd expect.
    return <div className="row">{row.map(this.renderItem)}</div>;

  renderItem: function(item) {
    return <div className="col-sm-3">{item}</div>;

Here’s a working example of this on JSBin: https://jsbin.com/hawoya/edit?js,output

Leave a comment