Home > Back-end >  How can I manage separate button presses using State?
How can I manage separate button presses using State?

Time:09-15

I am creating a simple quiz app. I am using state to manage if the answer buttons are pressed or not.

Currently, when the user presses an incorrect answer, all of the incorrect answers change in color. In hindsight, this should have been obvious.

My question is, If I have four possible answers per page, how can I keep incorrect answers separate from one another?

Relevant code:

const {colors} = useTheme();

var [isPress, setIsPress] = React.useState(false);

const wrongAnswer = () => {
    setIsPress(current => !current)
    if(isPress){
        console.log("isPress = true")
    }
    else{
        console.log("isPress = false")
    }
}


<Button
        onPress={wrongAnswer}
        style = {{
            backgroundColor: isPress ? 'red' : '#daeaf6',
             
            width: 150,
            height: 60,
            borderWidth: 5,
            borderRadius: 15,
            borderColor: '#0a2941',
            marginRight: 40,
            marginLeft: 10}}
            >
            <Text style={{ color: isPress ? 'black' : '', textAlign:'center'}}>Belt</Text>
            
        </Button>

CodePudding user response:

You can set a unique id for each answer and you pass this id to the onPressAnswer function.

For example:

const [chosenId, setChosenId] = useState('')

const onPressAnswer = (id) => setChosenId(id)

<Button
  onPress={() => onPressAnswer('answer1')}
  style={{
    backgroundColor: chosenId === 'answer1' ? 'red' : '#daeaf6',

    width: 150,
    height: 60,
    borderWidth: 5,
    borderRadius: 15,
    borderColor: '#0a2941',
    marginRight: 40,
    marginLeft: 10
  }}>
  <Text style={{ color: chosenId === 'answer1' ? 'black' : '', textAlign: 'center' }}>Belt</Text>
</Button>
  • Related