This blog post is brought to you by the developer of BitBudget. BitBudget is an automated budgeting app for Android and iOS which syncs with your bank account and helps you avoid overspending. If you’d like to quit living paycheck-to-paycheck and get a better handle on your finances, download it today! https://bitbudget.io
Having trouble working with FlatList’s in React Native? Something I have been struggling to figure out recently is how to go about excluding certain items and rows when rendering a FlatList in React Native. For example, let’s say you have an array of items stored in either Redux or in React’s built-in component state and you want to remove the item? Well this is fairly straight forward, you just remove the item from the store and the FlatList will update accordingly. However, what if you want to keep the item in the store but you want to filter it out from your FlatList?
Unfortunately the React Native docs don’t mention how to do this exactly. Furthermore, I wasn’t able to find any blog posts or Stack Overflow answers regarding this either. However, I was able to stumble upon the answer today while experimenting, so here is the answer:
If you wish to skip, filter, remove, or omit an item from your FlatList, add some conditional logic to your <FlatListItem /> component’s render method so that it returns nothing <></> when passed a particular prop. For example, take a look at my GitHub gist below. In the example I have a list of three items stored in my my <App/>’s component state. The three items are called “foo”, “bar”, and “baz”. Now, in the <FlatListItem />’s render method I have added some logic which states if the item is equal to “bar”, render nothing <></>.
So that’s all there is to it! Break the items you wish to render off into their own class components, and then add some logic to render nothing <></> under some particular condition, and React Native will simply skip over that item when rendering the FlatList.