I have a form which the user can select one of three options for membership. I an render the screen correctly but the button toggle isn't working. When I click on the other buttons the tick still stays on the first option. Here is my code
<View style={styles.mainview}>
<ListView
dataSource={this.state.dataSource}
renderRow={(rowData) =>
<TouchableHighlight onPress={() => this.toggleOneYear(rowData.id, rowData.i)} style={styles.registerButton} underlayColor='#ffffff'>
<View style={styles.detailBoxTick}>
{renderIf(rowData.i == 1)(
<Image style={styles.imageTickStyle} source={this.state.payoneyear ? Images.rememberTickImg : Images.rememberUnTickImg} />
)}
{renderIf(rowData.i == 2)(
<Image style={styles.imageTickStyle} source={this.state.paytwoyear ? Images.rememberTickImg : Images.rememberUnTickImg} />
)}
{renderIf(rowData.i == 3)(
<Image style={styles.imageTickStyle} source={this.state.paythreeyear ? Images.rememberTickImg : Images.rememberUnTickImg} />
)}
<Text style={styles.tickBoxText}>
{rowData.card_duration} years Membership ${rowData.price}
</Text>
</View>
</TouchableHighlight>
}
enableEmptySections
/>
</View>
toggleOneYear(id, counter) {
if (counter == 1) {
console.log('counter ', counter)
console.log('payoneyear ', this.state.payoneyear)
this.setState(
{
payoneyear: true,
paytwoyear: false,
paythreeyear: false
}
)
console.log('payoneyear ', this.state.payoneyear)
}
else if (counter == 2) {
console.log('counter ', counter)
console.log('payoneyear ', this.state.paytwoyear)
this.setState(
{
payoneyear: false,
paytwoyear: true,
paythreeyear: false
}
)
console.log('paytwoyear ', this.state.paytwoyear)
}
else if (counter == 3) {
console.log('counter ', counter)
this.setState(
{
payoneyear: false,
paytwoyear: false,
paythreeyear: true
}
)
}
}
What am I doing wrong in the above code? can some one please help. thanks in advance
It looks like you need to update the dataSource
with new rowData. I guess you are trying to increment rowData.i
with each touchableHighlight onPress?
The 3rd parameter of renderRow is rowID
. We will need this to know which row we need to update. You can pass it to toggleOneYear
or put the following in TouchableHighlight onPress:
var newArray = this.state.db.slice();
newArray[rowID] = {
// increment i, keep between 1-3
i: newArray[rowID].i + 1 > 3 ? 1 : newArray[rowID].i + 1,
};
this.setState({
dataSource: this.state.dataSource.cloneWithRows(newArray),
db: newArray,
});
I'm unsure what your intentions are with the payxxxyear
state variables as those are only 3 properties and you are rendering list data so I assume you have many TouchableHighlights that will be using same state. Seems it should probably use data source state instead?
BTW, ListView has been deprecated in latest RN versions. https://facebook.github.io/react-native/docs/listview.html#renderrow