ListView grid in React Native

You need to use a combination of flexbox, and the knowledge that ListView wraps ScrollView and so takes on its properties. With that in mind you can use the ScrollView’s contentContainerStyle prop to style the items.

var TestCmp = React.createClass({
    getInitialState: function() {
      var ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
      var data = Array.apply(null, {length: 20}).map(Number.call, Number);
      return {
        dataSource: ds.cloneWithRows(data),
      };
    },

    render: function() {
      return (
        <ListView contentContainerStyle={styles.list}
          dataSource={this.state.dataSource}
          renderRow={(rowData) => <Text style={styles.item}>{rowData}</Text>}
        />
      );
    }
});

Just a ListView with some dummy data. Note the use of contentContainerStyle. Here’s the style object:

var styles = StyleSheet.create({
    list: {
        flexDirection: 'row',
        flexWrap: 'wrap'
    },
    item: {
        backgroundColor: 'red',
        margin: 3,
        width: 100
    }
});

We tell the container we want items in a wrapping row, and the we set the width of each child object.

Screenshot

Leave a Comment