How to prevent a user from tapping a button twice in React native?
i.e. A user must not be able tap twice quickly on a touchable highlight
To prevent multiple button clicks in React: Set an onClick prop on the button, passing it a function.
React Native touchableopacity provide a disabled attribute to disable touchableopacity, you have to just pass true in the disabled attribute like the below example.
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.
To check if a string is empty in React, access its length property and check if it's equal to 0 , e.g. if (str. length === 0) {} . If the string's length is equal to 0 , then the string is empty, otherwise it isn't empty.
https://snack.expo.io/@patwoz/withpreventdoubleclick
Use this HOC to extend the touchable components like TouchableHighlight, Button ...
import debounce from 'lodash.debounce'; // 4.0.8 const withPreventDoubleClick = (WrappedComponent) => { class PreventDoubleClick extends React.PureComponent { debouncedOnPress = () => { this.props.onPress && this.props.onPress(); } onPress = debounce(this.debouncedOnPress, 300, { leading: true, trailing: false }); render() { return <WrappedComponent {...this.props} onPress={this.onPress} />; } } PreventDoubleClick.displayName = `withPreventDoubleClick(${WrappedComponent.displayName ||WrappedComponent.name})` return PreventDoubleClick; }
Usage
import { Button } from 'react-native'; import withPreventDoubleClick from './withPreventDoubleClick'; const ButtonEx = withPreventDoubleClick(Button); <ButtonEx onPress={this.onButtonClick} title="Click here" />
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