React Native ListView with Section Headers

Daryl Rowland
2 min readJan 11, 2016

--

I’ve completely fallen for ReactNative over the past few months. It makes app development much much easier, but one component I always struggle with is the ListView.

I’ve not found any articles yet that explain how to use the ListView’s section headers in a a nice clear and simple way, so this article is going to do exactly that…

What are we trying to do?

We basically want a ListView component that shows our rows in categories. E.g. we have a list of food, and instead of just showing it in a long list, we want to show it by category, like this…

The data source

So our data looks like this:

We need to turn this data into an object map instead of an array, where the categories are the key.

So the code does that is this:

Set the initial state

Ok, now we have the data wrangled into the format we need, lets look at the code needed to setup the ListView:

Here all we are doing is creating a new data source (line 3), and telling it that a row or section has changed if any part of the data changes (lines 4–6).

Then in line 9, we use that dataSource, and the ReactNative cloneWithRowsAndSections method to turn our foodMap into a ListView’s data source.

That’s it! That’s the hard part done. It seems complicated at first, but once you’ve figured out what’s going on, its actually not that hard at all.

Rendering the List View

Now all that’s left to do is render the ListView, its rows and its section headers.

The ListView can be rendered like this:

The only different part here to a normal ListView with just rows and not sections, is the renderSectionHeader property. You use this property to provide your render code for each section header. So, for example, your rendering code might look like this:

Note that it is the second parameter passed to renderSectionHeader that you use to get the key/title/id of the section.

--

--