I created a checkbox inside my flatlist but when I click on the checkbox all the check boxes will render. I want to render the checkbox I press not the entire checkboxes. This is my code.
JavaScript
x
32
32
1
const ScreenCart = () => {
2
const [checked, setChecked] = useState(false)
3
const renderItem = ({ item, index }) => {
4
return (
5
<View style={styles.list}>
6
<View style={{ flexDirection: 'row' }}>
7
<CheckBox
8
checkBoxColor={COLORS.ORANGE}
9
isChecked={checked}
10
onClick={() => setChecked(!checked)}
11
/>
12
<Image
13
source={item.image}/>
14
<View>
15
<Text numberOfLines={1} style={[styles.item, { width: 210 * rate }]}>{item.name}
16
</Text>
17
</View>
18
</View>
19
</View>
20
)
21
}
22
return (
23
<View style={{ backgroundColor: COLORS.WHITE, flex: 1 }}>
24
<View style={{ flex: 1 }}>
25
<Flatlist
26
data={TEMP_DATA_CART}
27
renderItem={renderItem}
28
keyExtractor={(item) => item.id.toString()}>
29
/>
30
</View>
31
)
32
this is my data.
JavaScript
1
11
11
1
TEMP_DATA_CART = [
2
{
3
id: '1', image: IMAGES.imgPromote, name: 'Sữa tắm Prunus - Premier Herb', value: 180000, quantity: 1, checked: false,
4
},
5
{
6
id: '2', image: IMAGES.imgPromote, name: 'Sữa tắm Prunus - Premier Herb', value: 180000, quantity: 1, checked: false,
7
},
8
{
9
id: '3', image: IMAGES.imgPromote, name: 'Sữa tắm Prunus - Premier Herb', value: 180000, quantity: 1, checked: false,
10
},
11
Advertisement
Answer
you set a global state so it is selecting checkbox for all items
remove this
JavaScript
1
2
1
const [checked, setChecked] = useState(false)
2
set array of selected id’s
JavaScript
1
2
1
const [checked, setChecked] = useState([]);
2
on press set id in array and set check status from array
JavaScript
1
15
15
1
<CheckBox
2
checkBoxColor={COLORS.ORANGE}
3
isChecked={checked.includes(item.id)}
4
onClick={() => {
5
const newIds = [checked];
6
const index = newIds.indexOf(item.id);
7
if (index > -1) {
8
newIds.splice(index, 1);
9
} else {
10
newIds.push(item.id)
11
}
12
setChecked(newIds)
13
}}
14
/>
15
and in flatlist set extraData
prop
JavaScript
1
7
1
<Flatlist
2
data={TEMP_DATA_CART}
3
renderItem={renderItem}
4
extraData={checked}
5
keyExtractor={(item) => item.id.toString()}>
6
/>
7
to retrive selected id’s you can get from checked
array