How do I make pressedItem be remembered and not changed on next onPress, to make it deselect if only the function is called again? Perhaps the ids to be remembered in an array and the array alters its length between pressedItem and dePressedItem?
const [pressedItem, setPressedItem] = useState(null);
let selected = [];
const changeColor = (itemid) => {
setPressedItem(itemid);
}
};
<FlatGrid data={interesi}
style={tw``}
spacing={10}
renderItem={({ item }) => (
<TouchableWithoutFeedback onPress={() => changeColor(item.id)}>
<View style={ pressedItem === item.id ? item.firstStyle : item.secondStyle }>
<Text style={tw`text-black`}>{item.english}</Text>
CodePudding user response:
If no other ID can be pressed you can use:
const changeColor = (itemid) => {
if (!pressedItem) {
setPressedItem(itemid);
}
};
If you are looking to not press the same id as before then:
const changeColor = (itemid) => {
if (pressedItem !== itemid) {
setPressedItem(itemid);
}
};
EDIT:
Updating the answer based on comments. Then you would need to do something like holding a map of the pressed state of the itemid
:
const [pressedItems, setPressedItems] = useState({});
let selected = [];
const changeColor = (itemid) => {
pressedItems[itemid] = !pressedItems[itemid];
setPressedItem(pressedItems);
};
CodePudding user response:
You should add the id of your item to an array as you said:
const [pressedIds, setPressedIds] = useState<number[]>([]);
const isMyIdPressed = (id: number): boolean => {
return pressedIds.include(id);
}
It will return true if your array contains your id and if not it will return false.
Whenever you press an id, just check if it is in the array, if yes add the id to the array and if no remove it from the array.