How to remove a item/index from a FlatList in react native?
General pattern is to pass a uniquely identifiable id
(key, index, etc...) to your delete handler and filter your data on values that don't equal that key. This returns a new array without that entry to store in state.
deleteItemById = id => {
const filteredData = this.state.data.filter(item => item.id !== id);
this.setState({ data: filteredData });
}
render() {
...
return (
<FlatList
data={data} // Assuming this is `this.state.data`
keyExtractor={({item}) => item.id}
renderItem={({item}) => (
<View style={styles.container}>
<SwipeView
...
onSwipedLeft={() => this.deleteItemById(item.id)}
...
/>
</View>
)}
/>
);
}
Using a curried handler. This saves using an anonymous callback by setting the callback to be an event handler with the id
enclosed in the function scope.
deleteItemById = id => () => {
const filteredData = this.state.data.filter(item => item.id !== id);
this.setState({ data: filteredData });
}
render() {
...
return (
<FlatList
data={data} // Assuming this is `this.state.data`
keyExtractor={({item}) => item.id}
renderItem={({item}) => (
<View style={styles.container}>
<SwipeView
...
onSwipedLeft={this.deleteItemById(item.id)}
...
/>
</View>
)}
/>
);
}
Pass an Id of the item to onSwipeLeft={this.deleteItem(item.id)}
and update the data using setState.
state = {
data: [{
title: 'Hello world',
id: 'hello'
},{
title: 'World says hello',
id: 'say'
}]
}
deleteItem = (id) => {
this.setState({
data: this.state.data.filter(item => item.id !== id)
})
}