Filter data using .filter() method in React Native

Filter function is used to filter the data from array with specific condition. This filter function gives an another array with filtered data as an output.

In the below example, we use the Flatlist to render a random users data using the free API provided by randomuser.me.

randomuser.me is an amazing free API for testing.

randomuser.me

In the top of Flatlist, I place textInput which is again a basic component of react native and placed one search icon on the right to search for a specific data.Also in this example the search is done as the user type anything in the input text.

So, without further wasting time let’s start writing the code.

Define state variables

constructor(props) {
    super(props);

    this.state = {
      users: [],
      searchText: '',
      filteredData: [],
    };
  }

Fetch the data from the API in componentDidMount

componentDidMount() {
    fetch('https://randomuser.me/api/?page=1&results=10').then(res =>
      res
        .json()
        .then(res => {
          this.setState({
            users: res.results,
          });
        })
        .catch(err => {
          console.log(err);
        }),
    );
  }

Now, place the input control, search icon and Flatlist to render the list.

<View style={{flex: 1, marginHorizontal: wp(20)}}>
        <View
          style={{
            flexDirection: 'row',
            alignItems: 'center',
            justifyContent: 'space-between',
          }}>
          <TextInput
            onChangeText={text => this.saveSearchedText(text)}
            style={{
              backgroundColor: Colors.WHITE,
              flex: 1,
              marginTop: hp(10),
              borderRadius: 6,
            }}
          />
          <Pressable onPress={() => this.onSearchText()}>{SEARCH}</Pressable>
        </View>
        <FlatList
          style={{flex: 1, marginTop: hp(20)}}
          keyExtractor={item => item.id}
          renderItem={({item}) => (
            <View
              style={{
                backgroundColor: Colors.WHITE,
                borderRadius: 6,
                marginBottom: hp(10),
              }}>
              <Text>{item.name.first}</Text>
              <Text>{item.email}</Text>
            </View>
          )}
          data={
            this.state.searchText.length > 0
              ? this.state.filteredData
              : this.state.users
          }
        />

Filter the data from the list based on firstname and email from the list

saveSearchedText(searchText) {
    var filteredData = this.state.users.filter(item => {
      return (
        item.name.first
          .toLowerCase()
          .match(this.state.searchText.toLowerCase()) ||
        item.email.toLowerCase().match(this.state.searchText.toLowerCase())
      );
    });
    this.setState({
      filteredData,
      searchText,
    });
  }

Here, the saveSearchedText function is used to filter the data, it filter the data according to the firstname and email.

To do the filter we used the .filter() method which takes the array and check for the condition whatever we write in the filter funtion.

Here, we used the .match function inside the filter function which matches the searched text which user wrote in the input field with the item data.

Also the or (||) operator is used because here we have to filter from both either the name is matched or the email is matched means that if the searched text is matched from firstname or email it filters that item and gives the collections of filtered items as an output.

So, hope you liked this post and learned something from here. Thanks

Renish

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top