Reputation: 539
I am using '@react-native-community/checkbox'
as I am retrieving data from database and rendering it whiting checkboxes using map function, the problem is when I check one box all boxes checked as well and same when I uncheck
the problem is with state of each checkbox but I have no idea how to handle that as I want to make only sleeted checkbox being checked and get all its data into one array for further process.
here the data I am rendering as checkboxes:
{"id": "12345", "price": 5, "text": "Reload"}
and this is the code of map function:
{data.map((b, index) => {
return (
<View key={b.id} style={{ flex: 1, flexDirection: 'column', width: windowWidth, paddingLeft: 15, paddingRight: 15 }}>
<View style={{ flexDirection: 'row-reverse', alignItems: 'center', justifyContent: 'space-between' }}>
<CheckBox
disabled={false}
value={checked}
onValueChange={(newValue) => { setIschecked(newValue) }}
/>
<Text>{b.text} </Text>
</View>
<View style={{ flexDirection: 'row', alignItems: 'center' }}>
<Text style={{ fontSize: 10, fontWeight: 'bold', color: COLORS.darkgray }}>
{" USD " + b.price}
</Text>
</View>
</View>
)
})}
I found a question same as my problem exactly which this one but unfortunately that doesn't work for me
thanks and advance
Upvotes: 1
Views: 2955
Reputation: 11591
You'll have to store the state of your checkboxes separate from the data itself, in React state.
First create an empty object on first render, this will act as a map of checkbox id
s to their checked value:
const [checked, setChecked] = React.useState({});
Inside your map
you can find the value of that particular checkbox based on b.id
:
value={checked[b.id]}
Finally in your callback, make sure you update the right value in checked
also based on b.id
:
onValueChange={(newValue) => { setChecked({...checked, [b.id]: newValue}) }}
Put it all together:
const [checked, setChecked] = React.useState({});
// rest of your render function
{data.map((b, index) => {
return (
<View key={b.id} style={{ flex: 1, flexDirection: 'column', width: windowWidth, paddingLeft: 15, paddingRight: 15 }}>
<View style={{ flexDirection: 'row-reverse', alignItems: 'center', justifyContent: 'space-between' }}>
<CheckBox
disabled={false}
value={checked[b.id]}
onValueChange={(newValue) => { setChecked({...checked, [b.id]: newValue}) }}
/>
<Text>{b.text} </Text>
</View>
<View style={{ flexDirection: 'row', alignItems: 'center' }}>
<Text style={{ fontSize: 10, fontWeight: 'bold', color: COLORS.darkgray }}>
{" USD " + b.price}
</Text>
</View>
</View>
)
})}
Upvotes: 3