How do I use React Native onLongPress properly?

26.3k views Asked by At

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.

3

There are 3 answers

0
zhou Dai On

You can test on a IOS simulator or in the release package.

2
romin21 On

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.

0
AlainIb On

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