Sumit
Sumit

Reputation: 27

how can i dynamically bind each state to each checkbox when using map function

I m doing something like this but the value is been taken as string and not as a variable with boolean value

        {question.data.map((value, i) => (
            <View style={{ flexDirection: 'row', alignItems: 'center', justifyContent: 'center' }}>
                <CheckBox value={`this.state.checked${i}`} onValueChange={() => this.toggleCheckBox(i)} />
                <Text>{value.question}</Text>
            </View>
            ))
        }

this is my toggleCheckBox method

      toggleCheckBox(i) {
         this.setState({ [`checked${i}`]: ![`this.state.checked${i}`] });
      }

need help.

Upvotes: 0

Views: 41

Answers (1)

Katherine R
Katherine R

Reputation: 1158

The issue is with adding string interpolation around this.state

toggleCheckBox(i) {
 this.setState({ [`checked${i}`]: !this.state[`checked${i}`] });
}


{question.data.map((value, i) => (
    <View style={{ flexDirection: 'row', alignItems: 'center', justifyContent: 'center' }}>
    <CheckBox value={this.state[`checked${i}`]} onValueChange={() => this.toggleCheckBox(i)} />
    <Text>{value.question}</Text>
    </View>
    ))
}

Upvotes: 1

Related Questions