How to Use Filter Method in React Native

Last Updated on December 13, 2020.

According to the official documentation, The filter() method creates a new array with all elements that pass the test implemented by the provided function. You can use Filter method to avoid use of for and while loops and it transform one array into another after ‘filtering’.

In the following example, I have a FlatList with an array as data. I want to remove the element named ‘one’ from the array and hence, I created a function named onPress where I use filter function. When the button is clicked the array would be filtered and all the ‘one’ elements would be removed.

As you can see, the using Filter function in React Native is pretty easy.

Class based component

import React, { Component } from 'react';
import { View, Text, FlatList, Button } from 'react-native';

export default class componentName extends Component {
  constructor(props) {
    super(props);
    this.state = {
      data: ['one','two','three','four','five','six','one','one']
    };
  }

  onPress=()=>{
    const newData = this.state.data.filter((item)=>{
      return item !== 'one';
    })
    this.setState({
    data: newData
    });
  }

  render() {
    return (
      <View style={{margin: 10, justifyContent:'center', alignItems:'center'}}>
        <FlatList
        data={this.state.data}
        renderItem={({item}) => <Text>{item}</Text>}
        />
        <Button
        onPress={this.onPress}
        title="Click here to filter"
        color="#841584"
        />
      </View>
    );
  }
}

Function based component

import React, {useState} from 'react';
import {View, Text, FlatList, Button} from 'react-native';

const App = () => {
  const [data, setData] = useState([
    'one',
    'two',
    'three',
    'four',
    'five',
    'six',
    'one',
    'one',
  ]);

  const onPress = () => {
    const newData = data.filter((item) => {
      return item !== 'one';
    });
    setData(newData);
  };

  return (
    <View style={{margin: 10, justifyContent: 'center', alignItems: 'center'}}>
      <FlatList data={data} renderItem={({item}) => <Text>{item}</Text>} />
      <Button onPress={onPress} title="Click here to filter" color="#841584" />
    </View>
  );
};

export default App;
Before using Filter Method
After using filter method

Leave a Reply

%d bloggers like this: