Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use React Native onLongPress properly?

I have a simple piece of code that's just a TouchableOpacity with a onLongPress prop, but it does not seem to be working.

<TouchableOpacity delayLongPress={10} onLongPress={()=>{console.log("pressed")}} activeOpacity={0.6}>
  <Text>BUTTON</Text>
</TouchableOpacity>

I've tried removing the delay prop but that still doesn't work. Changing onLongPress to onPress does seem to work however, but I want the long press functionality. I'm testing this on an Android simulator.

like image 371
Nerdragen Avatar asked Nov 28 '18 18:11

Nerdragen


People also ask

How do you handle the long press in react-native?

These long presses can be handled by passing a function to the onLongPress props of any of the "Touchable" components.

What do we use to respond properly for touches in react-native?

If you're looking for a more extensive and future-proof way to handle touch-based input, check out the Pressable API. A wrapper for making views respond properly to touches. On press down, the opacity of the wrapped view is decreased, dimming it.

How do you style TouchableOpacity in react-native?

To create custom buttons, you need to customize the <TouchableOpacity /> component and include the <Text /> component inside of it to display the button text. const AppButton = ({ onPress, title }) => ( <TouchableOpacity onPress={onPress} style={styles. appButtonContainer}> <Text style={styles.

How do you make a view touchable in react-native?

You will have to wrap your View inside TouchableHighlight or Opacity etc. I figured out a different way to solve my problem using pointerEvents={'box-none'} on my container View and wrapped the image in a View and gave it pointerEvents={'none'}.


2 Answers

According to this issue this happens randomly, after testing on a real device with React Native Debugger enabled. Disabling React Native Debugger will make your problem go away.

like image 183
romin21 Avatar answered Oct 22 '22 16:10

romin21


if you want to show a view on long press and hide it on release :

<TouchableOpacity
    onPress={this._onPress}
    onLongPress={this._onLongPress}
    onPressOut={this._onPressOut}
>
            ....
</TouchableOpacity>



_onLongPress = () => {
    this.setState({
        modalVisible: true
    })
}
_onPressOut = () => {
    this.setState({
        modalVisible: false
    })
}
like image 32
AlainIb Avatar answered Oct 22 '22 15:10

AlainIb