How to Use Filter Method in React Native
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 the Filter method to avoid the use of for and while loops and it transforms one array into another after ‘filtering’.
You can use it as given below.
const newData = data.filter(item => {
return item !== 'one';
});
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 a 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.
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;
That’s how you use Filter method in react native.