Anthon Santhez
Anthon Santhez

Reputation: 444

How to pass prop with the Pressable onPress attribute or with any other attribute or any alternative method?

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);
  }


};

Upvotes: 0

Views: 1338

Answers (1)

vinayr
vinayr

Reputation: 11244

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);
  }
}

Upvotes: 2

Related Questions