Please i need help trying to get the value/state of each selected checkbox in my react native project.
What I'm trying to do actually is to click on a button that navigates to "SelectProducts" screen. then the screen shows a list of items to select using checkboxes. I put the checkbox I imported from expo in a loop like the following:
import React, {useState, useEffect} from 'react'
import { StyleSheet, Text, View, Alert, Image, ScrollView, TouchableOpacity } from 'react-native';
import {useNavigation} from '@react-navigation/native';
import Checkbox from 'expo-checkbox';
const SelectProducts = ({route}) => {
const navigation = useNavigation();
const [checkedBox, setCheckedBox] = useState([]);
const [itemList, setItemList] = useState([]);
{itemList.map((item, index) => (
<View key={item.id} style={styles.checkboxContainer}>
<Checkbox
value={checkedBox[index]}
onValueChange={() => {
let checkedBox = [];
checkedBox[index] = !checkedBox[index];
setCheckedBox(checkedBox);
// console.log(setCheckedBox(checkedBox));
}}
color={checkedBox ? '#800080' : undefined}
style={styles.checkbox}
/>
</View>
))}
}
export default SelectProducts;
The code above is just a part of the entire code in the "SelectProducts" screen where I'm having issues. Please let me know what I'm not during right here.
So, after selecting the checkboxes for the items I want to include when recording a sales order, the system should get the price, item name, and picture to send back to the previous screen in order to calculate the total sum, etc. when done with the item selection.
But the result I'm getting is very weird. There is now a list of items with checkboxes as expected, but once I select one of the checkboxes, then try to select another one, the previous checkbox will be unselected automatically for the current one to be selected. The checkbox selection is behaving exactly like normal radio buttons that only accept one input at a time. Meaning that my checkbox implementation isn't allowing multiple selections. This is the main challenge I'm facing at the moment.
I have even tried to print out the output of the value when selected but it's showing 'undefined'. I'm so confused here. I know this is simple to some of the developers here but I'm quite finding it hard to implement. It has already taken me some days now. Please help. Thanks!
PS: I'm currently using this guy's solution How to handle checkbox in loop react native . He used a class component implementation while I used a function component. But it's not working for me. Don't know why. Please kindly help me look into it.
CodePudding user response:
This might help
itemList.map((item, index) => (
.....
<Checkbox
...
onValueChange={() => {
const newCheckedBox = [...checkedBox];
newCheckedBox[index] = !newCheckedBox[index];
setCheckedBox(newCheckedBox);
}}
...
/>
....
))