I have a TouchableHighlight
wrapping a Text
block that when tapped, opens a new scene (which I'm using react-native-router-flux).
It's all working fine, except for the fact that if you rapidly tap on the TouchableHighlight
, the scene can render twice.
I'd like to prevent the user from rapidly being able to tap that button.
What is the best way to accomplish this in Native? I looked into the Gesture Responder System, but there aren't any examples or anything of the sort, which if you're new, like me, is confusing.
To prevent multiple button clicks in React: Set an onClick prop on the button, passing it a function. When the button gets clicked, set its disabled attribute to true .
Tapping any button will fire the respective onPress callback and dismiss the alert. By default, the only button will be an 'OK' button. This is an API that works both on Android and iOS and can show static alerts.
Use the disabled prop to disable a button in React, e.g. <button disabled={true}>Click</button> . You can use the prop to conditionally disable the button based on the value of an input field or another variable or to prevent multiple clicks to the button. Copied!
What you're trying to do is you want to limit your on tap callbacks, so that they will only run ONCE.
This is called throttling, and you can use underscore
for that:
Here's how:
_.throttle(
this.thisWillRunOnce.bind(this),
200, // no new clicks within 200ms time window
);
Here's how my react component looks after all.
class MyComponent extends React.Component {
constructor(props) {
super(props);
_.throttle(
this.onPressThrottledCb.bind(this),
200, // no new clicks within 200ms time window
);
}
onPressThrottledCb() {
if (this.props.onPress) {
this.props.onPress(); // this only runs once per 200 milliseconds
}
}
render() {
return (
<View>
<TouchableOpacity onPress={this.onPressThrottledCb}>
</TouchableOpacity>
</View>
)
}
}
I hope this helps you. In case you wanna learn more check this thread.
The following works by preventing routing to the same route twice:
import { StackNavigator, NavigationActions } from 'react-navigation';
const App = StackNavigator({
Home: { screen: HomeScreen },
Details: { screen: DetailsScreen },
});
// Prevents double taps navigating twice
const navigateOnce = (getStateForAction) => (action, state) => {
const { type, routeName } = action;
return (
state &&
type === NavigationActions.NAVIGATE &&
routeName === state.routes[state.routes.length - 1].routeName
) ? state : getStateForAction(action, state);
};
App.router.getStateForAction = navigateOnce(App.router.getStateForAction);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With