rikesan rikesan - 7 months ago 60
iOS Question

Continuously increasing counter with long press React Native

I have a button next to a

that increases its counter when pressed.

<TouchableWithoutFeedback onPress={() => {this.increaseAmount(step, rowID)}}>
<View style={styles.amountPlusButtonContainer}>
<Text style={styles.amountButtonText}>+</Text>

It currently increases by 1 each time I tap the button. What I want to achieve is to keep increasing the counter for as long as the user is pressing it.

I have tried to use
but I don't know exactly when to stop it nor if it's the right approach to this problem.


I was able to make it work using the Animated API. A reference I used (besides the official documentation) was http://browniefed.com/blog/react-native-press-and-hold-button-actions/

   var ACTION_TIMER = 3000;
   var listenerActive = true;

       pressAction: new Animated.Value(0),
       value: 0,
   componentWillMount: function() {
     this.state.pressAction.addListener((v) => this.setState({value: v.value}));
   handlePressIn: function() {
     if(!listenerActive) {
       this.state.pressAction.addListener((v) => this.setValueAndChangeAmount(v.value));
       listenerActive = true;
     Animated.timing(this.state.pressAction, {
         duration: ACTION_TIMER,
         toValue: 67,
   handlePressOut: function() {
     this.setState({pressAction: new Animated.Value(Math.ceil(this.state.value))});
     listenerActive = false;

I used 3000ms and Math.ceil to maintain the same behavior as onPress since it cannot be used alongside onPressInand onPressOut.

Removing the listener in handlePressOut stops the counter. Setting a new pressAction with this.state.value resets the value to the one the counter stopped at.