skip to Main Content

I need to use a callback function for the mouse click event. Below code is working in React web app:

const checkAnswer = (e: React.MouseEvent<HTMLButtonElement>) => {
    const answer = e.currentTarget.value  // here .value property is undefined and gives error in React-Native. Just e.currentTarget is defined.
    const correct = questions[number].correct_answer === answer
    if(correct) setScore(prev => prev + 1)
  }

But I couldn’t apply it on React Native (mobile) for Pressable or TouchableOpacity.

This is the render part of React web app’s code:

<button value={answer} onClick{checkAnswer} />

and I try to apply it on React Native. The value will be passed to button’s value. But there is no "value" option in native’s Pressable component. Therefore I am confused

Any help?

2

Answers


  1. you can determine touch events by following

    <View onTouchStart={(e) => {console.log('touchMove',e.nativeEvent)}} />
    
    Login or Signup to reply.
  2. Here is some similar scenario what I could able to understand from the question.

    1. There is a Score state which will store the user’s score of a quiz game.
    2. There is a array of question where all the options and correct option are given.
    3. There will be a button for the option, if user choose a option, and based on that it will validate if user is correct or not.

    It might not be the exact scenario of you. But this could definitely help to solve your scenario.

    Here is a solution for the scenario => solution.

    If you click on the solution link you will be redirect to a page which is similar to the screenshot attached below. On very right you will find "My Device", "Android", "ios", choose any and run. Run via "my device" with expo app installed in your mobile if you don’t want to be in queue for some certain time.

    code_image

    Note: from your code this is for React web:

    <button value={answer} onClick{checkAnswer} />
    

    but in React Native you have to use a click event like this:

    <TouchableOpacity onPress={()=>buttonHandler()}></TouchableOpacity>
    

    Here ()=> and () extra need to be added to work a function properly.

    Also instead of .map() function you can use FlatList to improve your app. FlatList support lazy loading.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search