Home > Mobile >  How to determine mouse events in React Native (mobile)?
How to determine mouse events in React Native (mobile)?

Time:08-07

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?

CodePudding user response:

you can determine touch events by following

<View onTouchStart={(e) => {console.log('touchMove',e.nativeEvent)}} />

CodePudding user response:

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 => 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.

If you found this answer helpful please upvote this answer.

  • Related