I am creating a React Native App in which I am using the Checkbox in a javascript map function. Due to that when I check one checkbox it checks all the other checkboxes as well. How can manage to check the checkboxes separately and also I could check them multiple times from the map function list.

Here is the code for some references :

<Card noShadow style={styles.card}>
                    <CardItem header bordered>
                        <Text style={styles.header}>{string.color}</Text>
                    </CardItem>
                    {this.state.details.map((data, i) => {
                        return (
                            <List key={i}>
                                <CardItem>
                                    <CheckBox style={styles.checkbox}
                                        checked={this.state.checkedDefault} onPress={() => this.setState({ checkedDefault: !this.state.checkedDefault })} />
                                    <Text note style={styles.textWrap}>{data.name}</Text>
                                </CardItem>
                            </List>
                        )
                    })}
                </Card>

1 Answers

0
Shridhar Sharma On Best Solutions

You need to use object for that, change your render method like below

<Card noShadow style={styles.card}>
    <CardItem header bordered>
        <Text style={styles.header}>{string.color}</Text>
    </CardItem>
    {this.state.details.map((data, i) => {
        return (
            <List key={i}>
                <CardItem>
                    <CheckBox style={styles.checkbox}
                        checked={!!this.state.checkedDefault[i]}
                        onPress={
                            () => this.setState(state => {
                                const checkedDefault = {...state.checkedDefault};
                                checkedDefault[i] = !checkedDefault[i];
                                return { checkedDefault }
                            })
                        } />
                    <Text note style={styles.textWrap}>{data.name}</Text>
                </CardItem>
            </List>
        )
    })}
</Card>

don't forget to assign initial value for checkedDefault in state, like below

state = {
   //other values
   checkedDefault: {}
}

Also you can use an id property, if exists on the items in details array instead of i to assign the value in the object