I have a flatlist in my application and I want to enable a user to mark a particular list item as selected on Long press and provide a delete button to remove multiple items in one go. These are the behaviors I expect.
- If no items in the flatlist are selected, pressing an item opens a new screen with item details and back button takes you back to the flatlist.
- If no items are selected, long pressing an item marks it as selected. Every item pressed after any particular item is selected is marked as selected instead of opening the details screen.
- Items which are already selected and then pressed become unselected.
- If any number of items are selected, a delete button is rendered and pressing the back button unselects all items.
I have been able to achieve most of the first three behaviors but I am completly lost with the Back Handler. Here is my component with only the relevant code for brevity. Only the state array which contains the items selected for deletion and the listItem which is used as the RenderItem prop for the flatlist is shown.
const Home = (props) => {
const [deleteItems, setDeleteItems] = useState([]);
const renderItem = ({ item }) => {
let bb_OR_ub = item.useBy ? 'Use By ' : 'Best Before '
let exp_check = CheckExp(item, 1);
let listStyle = {};
if (exp_check === -1)
listStyle = { backgroundColor: '#ff9ea5' }
else if (exp_check === 0)
listStyle = { backgroundColor: '#fff185' }
if (deleteItems.indexOf(item.name) != -1) {
listStyle = { opacity: 0.3 }
}
return (
<ListItem
containerStyle={listStyle}
badge={
exp_check !== 1 ?
exp_check === -1 ? { status: 'error', value: `!` } : {
status: 'warning'
} : null
}
title={item.name}
subtitle={bb_OR_ub + item.date}
bottomDivider
leftAvatar={{ source: require('../shared/cexp.png'), imageProps: { resizeMode: 'contain' } }}
onPress={() => {
if (deleteItems.length == 0)
navigate('ExpiryDetails', { item })
else {
setDeleteItems([...deleteItems, item.name])
}
}}
onLongPress={() => {
if (deleteItems.indexOf(item.name) == -1 || deleteItems.length == 0) {
setDeleteItems([...deleteItems, item.name])
}
else {
setDeleteItems(deleteItems.filter(el => el != item.name))
}
}} />
);
}