How to Use Filter Method in React Native?

Nov 24, 2022 . Admin

In this tutorial,We will use the filter method in react native.you can easily use to filter method to react native app.

In the 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 five’ elements would be removed.

Step 1: Download Project

In the first step run the following command to create a project.

expo init ExampleApp
Step 2: App.js

In this step, You will open the App.js file and put the code.

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 !== 'five';
    });
    setData(newData);
  };

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

export default App;
Step 3: Run Project

In the last step run your project using the below command.

expo start

You can QR code scan in Expo Go Application on mobile.

Output:

It will help you...

#React Native