Repeat onPress action when holding button [react native]

This is rather a small recipe that I couldn’t find straightforwardly. Let’s say we have a button (TouchableHighligh, TouchableNativeFeedback, TouchableOpacity, TouchableWithoutFeedback and Button) that has onPress action that increases amount of something.

Pretty simple

Everybody can do that, it’s pretty simple. Now what will do ordinary user if you ask him to add 50 more? He will do what comes natural, just holding down button and wait until he hits the mark. But when you provided onPress to increase amount by one, it won’t do any more than that, onLongPress won’t help either, it just fires one function when users holds button for long enough period of time. So what now?

There are two more props you can pass to touchable component, onPressIn and onPressOut. They are, as the name suggests, called upon pressing down the button and releasing it.

So with simple code and one timer we can just create something like this.

Here we can see creating null object timer in the constructor of the component. Next are two functions, addOne which increases the state and with little bit of a delay calls itself again, stopTimer just clears the timeout. We can now use this two functions.

Touchable opacity gets in onPressIn prop that calls mentioned function addOne while onPressOut just clears the timer. The result is instant.

Keep adding

When you press you will just increase state by one as before, but holding the button down will keep increasing the state until you release.

It’s simple, but effective.

Like what you read? Give Pavol Fulop a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.