Prevent Double tap in React native

gourav.singhal picture gourav.singhal · Nov 3, 2017 · Viewed 35.1k times · Source

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

Answer

Patrick Wozniak picture Patrick Wozniak · Nov 10, 2017

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" />