Skip to content

Instantly share code, notes, and snippets.

@mcgaffin
Last active August 29, 2015 14:27
Show Gist options
  • Save mcgaffin/97ae840e34b5291e4e12 to your computer and use it in GitHub Desktop.
Save mcgaffin/97ae840e34b5291e4e12 to your computer and use it in GitHub Desktop.
React Native: add section headers to ListView

from facebook/react-native#1706

First I put this in my constructor function:

var getSectionData = (dataBlob, sectionID) => {
      return dataBlob[sectionID];
 }
var getRowData = (dataBlob, sectionID, rowID) => {
      return dataBlob[sectionID + ':' + rowID];
}
this.ds = new ListView.DataSource({
      getSectionData: getSectionData,
      getRowData: getRowData,
      rowHasChanged: (r1, r2) => r1 !== r2,
      sectionHeaderHasChanged: (s1, s2) => s1 !== s2
}) 

Then you have to create a dataBlob object, an array of sectionIDs, and an array of rowID arrays with the following formats:

var dataBlob = {
     'sectionID1' : { ...section1 data },
     'sectionID1:rowID1' : { ...row1 data },
     'sectionID1:rowID2' : { ..row2 data },
     'sectionID2' : { ...section2 data },
     'sectionID2:rowID1' : { ...row1 data },
     'sectionID2:rowID2' : { ..row2 data },
     ...
}

var sectionIDs = [ 'sectionID1', 'sectionID2', ... ]

var rowIDs = [ [ 'rowID1', 'rowID2' ], [ 'rowID1', 'rowID2' ], ... ]

Finally, you can create a valid dataSource for your list with:

this.ds.cloneWithRowsAndSections(dataBlob, sectionIDs, rowIDs)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment