Thursday, October 29, 2015

Overview

This post is all about creating a ListView using react-native. We’ll look at rows and sections. You can find more information about the ListView component here.

Content

I’ll first show the final code, then break it up into parts.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
'use strict';

var React = require('react-native');
var {
    Text,
    View,
    Component,
    StyleSheet,
    TouchableHighlight,
    ListView
} = React;

var sections = ["SectionTitle1", "SectionTitle2"]
var rowsBySection = {
    SectionTitle1: ["sec1 row1", "sec1 row2"],
    SectionTitle2: ["sec2 row1", "sec2 row2"]
};

class ListTest extends Component {
    constructor(props) {
        super(props);

        var {rowsBySection, sections} = this.generateListViewData();
        var ds = new ListView.DataSource({
            sectionHeaderHasChanged: (r1,r2) => r1 !== r2,
            rowHasChanged: (r1,r2) => r1 !== r2
        });

        this.state = {
            dataSource: ds.cloneWithRowsAndSections(rowsBySection, sections)
        };
    }

    generateListViewData() {
        return {rowsBySection, sections};
    }

    renderRow(rowData) {
        return (
            <TouchableHighlight
                style={styles.row}>
                    <Text>{rowData}</Text>
            </TouchableHighlight>
        );
    }

    renderSectionHeader(data, sectionName) {
        return (
            <View style={styles.section}>
                <Text>{sectionName}</Text>
            </View>
        );
    }

    render() {
        return (
            <ListView
                dataSource={this.state.dataSource}
                renderRow={this.renderRow.bind(this)}
                renderSectionHeader={this.renderSectionHeader.bind(this)}
            />
        );
    }
}

module.exports = ListTest;

This is the only confusing part in my opinion. This is what our data looks like. We have an array of strings for our sectionIds and they map to rows in the rowsBySection object. I believe that the rest of the code is pretty self explanatory.

1
2
3
4
5
var sections = ["SectionTitle1", "SectionTitle2"]
var rowsBySection = {
    SectionTitle1: ["sec1 row1", "sec1 row2"],
    SectionTitle2: ["sec2 row1", "sec2 row2"]
};

Random Posts