Contacts List Screen in React Native
We will be building a simple contacts list screen in React Native. This is how the final version of the app will look like.
Couple of things to notice here, sections are based on first letter of the first name and that letter is displayed as section header at the top.
We will be using SectionList component of react-native to implement this.
This is how the contacts data looks like. Usually you would fetch these contacts from a remote URI, but I have kept it as static for simplicity purposes.
Now in order to feed this data to our section list, we need to modify couple of things in data first.
Formatting data for SectionList
In comments you will see how formatted data is expected in SectionList (keys name can change). In our getData() function we are changing the structure of data and also adding another field called title which will serve the purpose of our section’s header title. Also, we have sorted data according to names under each title, as contacts list is also sorted.
Now to our main render function:
Data returned by above function is fed to sections property of SectionList. Another property ListHeaderComponent is used to render the header for the whole list. renderItem is responsible of how we want to display each row of our data. Here it takes a single item of each section’s array. keyExtractor is used to assign key to each row of list, here I am using item’s index which is unique for each item in my case. renderSectionHeader property is responsible to display the header for each section. Each element of data returned from from getData function is fed to this as section property, and here we are rendering a simple header row with text as section’s title which in our case is first letter of the names of same section.
Following these steps will lead you to implement a simple contacts app as in above image. The complete source code of this app can be found here under “contacts_list” branch.