Lucas
Lucas

Reputation: 47

How to change the border color of each item in the same TouchableOpacity in React Native?

I have a quiz screen like this. I want when clicking on any TouchableOpacity will change the color of the border, the rest will not. I fetch data of the question into two TouchableOpacity, one for the correct answer and one for three wrong answers. The correct answer is ok but when I try to click on an incorrect answer, all three incorrect changes the border color. I know because they are in the same TouchableOpacity but I don't know how to fix it. Any solutions? Image one, Image two

Upvotes: 0

Views: 475

Answers (1)

Joy Terence
Joy Terence

Reputation: 730

You need to have a state that holds the selected option and use this state value before deciding on the border color.

Why not make your _onPress() function pass something unique to the individual touchable element. Say, index? onPress={() => _onPress(2, index)}

and you could add it to state as follows:

_onPress(val, index) {
    this.setState({answer: val, selected: index})
} 

And then set borderColor as follows (in the touchable opacity for incorrect answers):

borderColor: (index == selected && answer == 2)? color1 : color2

Upvotes: 1

Related Questions