Home > Software engineering >  How to pass prop with the Pressable onPress attribute or with any other attribute or any alternative
How to pass prop with the Pressable onPress attribute or with any other attribute or any alternative

Time:08-08

I am trying to pass the answer string (of mapped answers) into handleButtonClick function where I will compare the answer with the correct answer. Here is the code that is creating the answer string:

      <View>
        {answers.map(answer => (
          <View key={answer}>
            <Pressable
              onPress={handleButtonClick} >
               <Text>
                  {answer}
               </Text>                
            </Pressable>
          </View>
        ))}
      </View>

And here is the code for handleButtonClick:

const handleButtonClick= () => {

  //check answer due to correct answer
  const correct = questions[number].correct_answer === answer;  // I am trying to pass the "answer" variable to here in order to make the comparison

  console.log("isCorrect = ", correct)

  //add score if answer is correct
  if (correct) {
    setScore(prev => prev   1);
  }


};

CodePudding user response:

Pass it like this:

<Pressable onPress={() => handleButtonClick(answer)} >
const handleButtonClick = (answer) => {
  const correct = questions[number].correct_answer === answer;

  console.log("isCorrect = ", correct)

  //add score if answer is correct
  if (correct) {
    setScore(prev => prev   1);
  }
}

  • Related