In Today’s article, we are going to see how to work with FlatLists in React Native and We will add a search bar as a header to the FlatList and filter the list, Also we will see what are spread operators and how to work with them.
Note: Make sure that you install react-native-elements package.
You can follow the below link to install it.
https://react-native-elements.github.io/react-native-elements/docs/getting_started.html
Watch Video Tutorial
So for this example we have the below variables
loading: false, data: [], temp: [], error: null, search: null
The ‘data’ variable is going to be the source for our FlatList in the UI, temp array will hold the copy of the original array which will be used for filtering the array, error will hold the array from the service, search will hold the search text in the SearchBar.
Service
With the help of below method, we will call a sample url and the setResult function will update the variables.
getData = async () => { const url = `https://jsonplaceholder.typicode.com/users`; this.setState({ loading: true }); try { const response = await fetch(url); const json = await response.json(); this.setResult(json); } catch (e) { this.setState({ error: 'Error Loading content', loading: false }); } }; setResult = (json) => { this.setState({ data: [...this.state.data, ...json], temp: [...this.state.temp, ...json], error: json.error || null, loading: false }); } [java] In the above method 'setResult' we are updating the data and temp variable mainly. Here you can use like below also [java] data: json
But you can use the spread operator as well like in the example above.
Spread Operator in the code helps to copy the data from json array to the data array.
Anyway both approach will work.
FlatList
Now we have the data, we can supply the source to FlatList.
Here we are adding the SearchBar as a header to the FlatList.
renderHeader = () => { return <SearchBar placeholder="Search Here..." lightTheme round editable={true} value={this.state.search} />; }; <FlatList ListHeaderComponent={this.renderHeader} data={this.state.data} keyExtractor={item => item.email} renderItem={({ item }) => ( <ListItem roundAvatar title={`${item.name}`} subtitle={item.email} /> )}
Filtering the List
Now we will filter the list based on what the user types in the SearchBar.
updateSearch = search => { this.setState({ search }, () => { if ('' == search) { this.setState({ data: [...this.state.temp] }); return; } this.state.data = this.state.temp.filter(function(item){ return item.name.includes(search); }).map(function({id, name, email}){ return {id, name, email}; }); }); };
Here we will filter on the temp array and update the data array which will finally be fed to the FlatList.
So its that simple to use FlatLists in React-Native.
Below is the complete Source Code.
Source Code
import React, { Component } from "react"; import { View, Text, FlatList, Button } from "react-native"; import { ListItem, SearchBar } from "react-native-elements"; class FlatListDemo extends Component { constructor(props) { super(props); this.state = { loading: false, data: [], temp: [], error: null, search: null }; } componentDidMount() { this.getData(); } getData = async () => { const url = `https://jsonplaceholder.typicode.com/users`; this.setState({ loading: true }); try { const response = await fetch(url); const json = await response.json(); this.setResult(json); } catch (e) { this.setState({ error: 'Error Loading content', loading: false }); } }; setResult = (res) => { this.setState({ data: [...this.state.data, ...res], temp: [...this.state.temp, ...res], error: res.error || null, loading: false }); } renderHeader = () => { return <SearchBar placeholder="Search Here..." lightTheme round editable={true} value={this.state.search} onChangeText={this.updateSearch} />; }; updateSearch = search => { this.setState({ search }, () => { if ('' == search) { this.setState({ data: [...this.state.temp] }); return; } this.state.data = this.state.temp.filter(function(item){ return item.name.includes(search); }).map(function({id, name, email}){ return {id, name, email}; }); }); }; render() { return ( this.state.error != null ? <View style={{ flex: 1, flexDirection: 'column',justifyContent: 'center', alignItems: 'center' }}> <Text>{this.state.error}</Text> <Button onPress={ () => { this.getData(); } } title="Reload" /> </View> : <FlatList ListHeaderComponent={this.renderHeader} data={this.state.data} keyExtractor={item => item.email} renderItem={({ item }) => ( <ListItem roundAvatar title={`${item.name}`} subtitle={item.email} /> )} /> ); } } export default FlatListDemo;
Good morning all,
I am new to React Native.
There’s this line of code `$ {item.name}` that I don’t understand. Especially the characters that surround $ {item.name}. Which character is it and how do I enter it on the keyboard?
I’m asking this because, when I replace these characters with single quotes ‘ ‘ , the code no longer works.
Thank you
You have to use the other quotes.
Thank you,
So, I only know of 2 quotes, the single (‘ ‘) and the double (” “). What other quotes are you talking about?
Hi James,
Please, I wait your answer….
Thank you,
So, I only know of 2 quotes, the single (‘ ‘) and the double (” “). What other quotes are you talking about?
Can you give same example for nested flatlist…