Splekke
Splekke

Reputation: 81

How to only select one checkbox in a React Native Android app?

I'm trying to set up my first Android app in React Native.

Now there's this card (react-native-component) with multiple checkboxes inside (see code below).

Every time I try to select only one checkbox, it somehow checks all of them.

I know it has something to do with multiple states, but I can't get it to work.

How can I only select one checkbox?

JavaScript file:

import React from "react";
import {StyleSheet, ActivityIndicator, ListView, Text, View, Alert, Platform, TouchableOpacity} from 'react-native';
import { Card, CheckBox, Button } from 'react-native-elements';

export default class AgendaItemVote extends React.Component {

    constructor(props) {
        super(props);
        this.state = { checked: false };
    }

    render(){
        return(
            <View style={styles.container}>
                <Card title="Titel Agendapunt">
                    <Text style={styles.paragraph}>
                        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus at sapien at tellus interdum finibus. Nunc sagittis tincidunt orci, non viverra ligula feugiat id. Phasellus eleifend massa neque, eu scelerisque enim feugiat ac.
                    </Text>

                    <View style={{flexDirection: 'row'}}>
                        <CheckBox
                            title='Ja'
                            checked={this.state.checked}
                            onPress={() => this.setState({
                                checked: !this.state.checked
                            })}
                        />
                         <CheckBox
                            title='Nee'
                            checked={this.state.checked}
                            onPress={() => this.setState({
                                checked: !this.state.checked
                            })}
                        />
                         <CheckBox
                            title='Onthouding'
                            checked={this.state.checked}
                            onPress={() => this.setState({
                                checked: !this.state.checked
                            })}
                        />

                    </View>
                    <View>
                        <Button
                            title="Indienen"
                        />
                    </View>
                </Card>
            </View>
        );
    }
}

const styles = StyleSheet.create({
    container: {
      flex: 1,
      alignItems: 'center',
      justifyContent: 'center',
      paddingTop: 40,
      backgroundColor: '#ecf0f1',
    },
    paragraph: {
      margin: 24,
      fontSize: 18,
      fontWeight: 'bold',
      textAlign: 'center',
      color: '#34495e',
    },
});

Upvotes: 0

Views: 8212

Answers (3)

Majid Parvin
Majid Parvin

Reputation: 5062

You have to have a specific state for each control. there is a solution for you:

   export default class AgendaItemVote extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            options: [
                {
                    title: 'Ja',
                    checked: false
                },
                {
                    title: 'Nee',
                    checked: false
                },
                {
                    title: 'Onthouding',
                    checked: false
                }
            ]
        };
    }

    render() {
        return (
            <View style={styles.container}>
                <Card title="Titel Agendapunt">
                    <Text style={styles.paragraph}>
                        Lorem ipsum dolor sit amet, consectetur adipiscing elit.
                        Vivamus at sapien at tellus interdum finibus. Nunc
                        sagittis tincidunt orci, non viverra ligula feugiat id.
                        Phasellus eleifend massa neque, eu scelerisque enim
                        feugiat ac.
                    </Text>

                    <View style={{ flexDirection: 'row' }}>
                        {this.state.options.map(opt => (
                            <CheckBox
                                title={opt.title}
                                checked={opt.checked}
                                key={opt.title}
                                onClick={() => {
                                  opt.checked = !opt.checked;
                                  this.setState({
                                        options: [
                                            ...this.state.options
                                        ]
                                    })
                            ></CheckBox>)
                        )}
                    </View>
                    <View>
                        <Button title="Indienen" />
                    </View>
                </Card>
            </View>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        alignItems: 'center',
        justifyContent: 'center',
        paddingTop: 40,
        backgroundColor: '#ecf0f1'
    },
    paragraph: {
        margin: 24,
        fontSize: 18,
        fontWeight: 'bold',
        textAlign: 'center',
        color: '#34495e'
    }
});

Upvotes: 1

Digember Dangwal
Digember Dangwal

Reputation: 49

I had a similar issue, after resolving the issue I am writing my answer here.

Consider the example below - (with hooks)

const checkboxComponent = () => {

  const [checkboxValue, setCheckboxValue] = React.useState([
   { label: 'Customer', value: 'customer', checked: false },
   { label: 'Merchant', value: 'merchant', checked: false },
   { label: 'None', value: 'none', checked: false },
 ])

 const checkboxHandler = (value, index) => {
   const newValue = checkboxValue.map((checkbox, i) => {
    if (i !== index)
      return {
        ...checkbox,
        checked: false,
      }
    if (i === index) {
      const item = {
        ...checkbox,
        checked: !checkbox.checked,
      }
      return item
    }
   return checkbox
 })
 setCheckboxValue(newValue)
 }    

return (
   <View>
    {checkboxValue.map((checkbox, i) => (
        <View style={styles.checkboxContainer} key={i}>
          <CheckBox
            value={checkbox.checked}
            onValueChange={(value) => checkboxHandler(value, i)}
          />
          <Text style={styles.label}>{checkbox.label}</Text>
        </View>
      ))}

   </View>
 )
}
export default checkboxComponent

Upvotes: 1

ravibagul91
ravibagul91

Reputation: 20765

The problem is here,

checked={this.state.checked}

When you set checked to true, every checkbox is getting checked as you are using this value to this.state.checked in every checkbox.

Remove the checked and onPress from all the checkboxes and if you want to get the value of checked checkbox then you can use ref.

For your reference:: Get the value of checkbox using ref in React

Upvotes: 0

Related Questions