I am currently trying to make this "project" work.
demo img
https://codesandbox.io/s/flatlisttesting-eiw0x
Expected behaviour:
a) clicking on element of FlatList should change their state resulting in the CheckBox being checked
b) clicking the "Select All" TouchableOpacity should result in all of the items' checkboxes being checked and clicking the TouchableOpacity again afterwards should uncheck the checkboxes
Result:
a) works as intended
b) When I click on an element (checking the CheckBox) and then try pressing the TouchableOpacity, the CheckBoxes are indeed checked, but when I click on the TouchableOpacity again it only unchecks the CheckBoxes that weren't previously checked(checked->unchecked)
Could anyone possibly shed some light on this problem?
Thanks in advance
It is generally not a good idea to keep a separate state inside the component, and also use another external data source, for a single data source. Here, your only data source is your array. So for a better convention, the only source of your FlatList should be the data you pass. So if you remove the extra state operations inside the CustomItem component, it will work as expected:
import { TouchableOpacity, View, Text, CheckBox } from "react-native";
import { useState } from "react";
export default function CustomItem({
item,
flatListData,
setFlatListData
}) {
function handlePress() {
setFlatListData(
flatListData.map((element) => {
if (item.id === element.id) {
return { ...item, isDone: !item.isDone };
}
return element;
})
);
}
return (
<TouchableOpacity onPress={handlePress} style={{ flexDirection: "row" }}>
<Text style={{ marginRight: 10 }}>{item.text}</Text>
<CheckBox value={item.isDone} onPress={handlePress} />
<Text>{JSON.stringify(item)}</Text>
</TouchableOpacity>
);
}
By doing that, the CustomItem will only rely on the data source and not need extra conditional renderings inside itself.
However, I also have one suggestion. Currently your Select All button does not work like a select all, but rather works like a toggle button. I would suggest you to modify it, so that it will select all if all items are not selected, and only uncheck all if all items is selected. It's up to you of course but the name and function does not look consistent.