react-native-controlled-listview v0.2.0
Why?
For performance reasons, React Native ListView
needs a ListView.DataSource
, so it can efficiently update itself. To benefit from these optimisations, any component wishing to render a ListView
needs to be stateful to hold the DataSource, and faff about with lifecycle methods to update it.
This library hides that statefulness and provides a simple, props-based API to render ListViews.
How-to
Installation:
npm i --save react-native-controlled-listview
Instead of dataSource
, controlled ListView
expects an array prop items
. Optionally, you can sort the list with sortBy
or group it into sections with sectionBy
:
- import { ListView } from 'react-native';
+ import ListView from 'react-native-controlled-listview';
// stateless function component
export default (props) => (
+ <ListView
- dataSource=...
+ items={props.people}
+ sortBy={(person) => person.lastName}
+ sectionBy={(person) => person.lastName[0]}
renderRow={(person) => (
<Text style={styles.row}>{person.lastName}, {person.firstName}</Text>
)}
renderSectionHeader={(sectionData, initial) => (
<Text style={styles.sectionHeader}>{initial}</Text>
)}
/>
);
Immutability
There is one gotcha. This component expects you to clone the items
prop when you want to ListView to update. If you are using Redux, this should already be the case.
The items
prop can be an instance of Immutable.List
, or an array. If using plain arrays, never mutate it in-place, or the ListView won't update.
See dataSourceShouldUpdate
on how to customise the update logic.
Props
items : any[] | Immutable.List
(required)
List data source.
sortBy : (a, b) => number | boolean
Sorts the list based on a comparator. Value can be one of type:
(a, b) => number
a standardArray#sort compareFunction.
(a, b) => boolean
a shorthand comparator: if returns true,a
comes first; if false,b
comes first.
sectionBy : (a, b) => string
Groups the list based on returned value and renders section headers for each group.
If using sectionBy
, you must also provide renderSectionHeader
rowHasChanged : (prevItem, nextItem) => boolean
Passed directly to ListView.DataSource
. constructor. Defaults to !Immutable.is(prevItem, nextItem)
, which performs a ===
comparison for plain objects.
sectionHeaderHasChanged : (prevSectionData, nextSectionData) => boolean
Passed directly to ListView.DataSource
. constructor. Defaults to prev !== next
.
dataSourceShouldUpdate : (prevProps, nextProps) => boolean
Controls when the data source should be updated. The default implementation is !Immutable.is(prevProps.items, nextProps.items)
, which performs a ===
comparison for plain arrays.
...ListView.props
All other properties, except dataSource
are passed directly to the underlying ListView.
Please note
This project is in a pre-release state. The API may be considered relatively stable, but changes may still occur.