Using React Native Flatlist

Replace React Native ScrollView with the new (and smarter) Flatlist

TAGS: react,react native,flatlist,scrollview,listview

4/05/2017

React Native v 0.43 introduces a suite of new components, including the FlatList, while the ListView component will soon be deprecated.

FlatList is great — it allows you to render a subset of items and, on scroll, render additional items. It also allows for “pull to refresh” functionality, and is a PureComponent, which should mean significant performance improvements in your project. However, React Native 43 requires the inclusion of an alpha candidate level version of react, which, in my case at least, wreaked a bit of havoc in trying to include.

Luckily, you can still use the components without going all-in on some early release versions of React and React Native.

To start, run the following script from your react native project root:


           mkdir -p node_modules/react-native/Libraries/Lists/ && \for file in ‘FlatList’ ‘MetroListView’ ‘SectionList’ ‘VirtualizedList’ ‘VirtualizedSectionList’ ‘ViewabilityHelper’ ‘VirtualizeUtils’; \ do curl https://raw.githubusercontent.com/facebook/react-native/master/Libraries/Lists/${file}.js > node_modules/react-native/Libraries/Lists/${file}.js; \ done
           

This will grab the new components from github, and put them in your node modules directory. Additionally, if you get a message similar to:


           Object is not a constructor (evaluating ‘new ViewabilityHelper(_this.props.viewabilityconfig)’)”
           

You may need to run:


           for file in 'FlatList' 'MetroListView' 'VirtualizedList' 'VirtualizeUtils' 'ViewabilityHelper'; \
do curl https://raw.githubusercontent.com/facebook/react-native/master/Libraries/Experimental/${file}.js > node_modules/react-native/Libraries/Experimental/${file}.js; \
done
           

Once this is done, you can include the FlatList component in your project:


           import FlatList from 'react-native/Libraries/Lists/FlatList'
           

FlatList requires only two props: the data you wish to render data={data} and renderItem={this.renderItem} which is a link to a function which will render out the list items you want from the data you pass. In my case, this looked something like:

<pre><code class="language-bash"> renderItem = (feedItem) => { const { item, index } = feedItem <Image source={item.image} key={`imageCard${index}` > <Text>{item.text}</Text> </Image> }

If you are working collaboratively on a project with others, and you want to ensure they can also use these components without having to repeat the curl commands above, you could include a postinstall step in your package.json which executes the commands automatically.