Skip to content

Instantly share code, notes, and snippets.

@ivmos
Created May 30, 2018 10:12
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ivmos/b6546de193349fcf54ea8581ea445a8d to your computer and use it in GitHub Desktop.
Save ivmos/b6546de193349fcf54ea8581ea445a8d to your computer and use it in GitHub Desktop.
import React, { Component } from 'react';
import { TouchableOpacity, TouchableHighlight } from 'react-native';
import { PropTypes } from 'prop-types';
/* eslint-disable no-invalid-this */
const debounce = function(callback, wait, context = this)
{
let timeout = null;
let callbackArgs = null;
const later = () => callback.apply(context, callbackArgs);
return function()
{
/* eslint-disable prefer-rest-params */
callbackArgs = arguments;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
};
};
/**
* Based on https://medium.com/@devmrin/debouncing-touch-events-in-react-native-prevent-navigating-twice-or-more-times-when-button-is-90687e4a8113,
* just made it more generic
*/
export default class TouchableDebounce extends Component
{
constructor(props)
{
super(props);
}
render()
{
const TouchableComponent = this.props.type == 'Opacity'
? TouchableOpacity
: TouchableHighlight;
return (
<TouchableComponent
style={this.props.style}
accessibilityLabel={this.props.accessibilityLabel}
raised={this.props.raised}
underlayColor={this.props.underlayColor}
activeOpacity={this.props.activeOpacity}
onPress={
debounce(() =>
{
this.props.onPress();
}, 500)
}
>
{this.props.children}
</TouchableComponent>
);
}
}
TouchableDebounce.propTypes =
{
accessibilityLabel : PropTypes.any,
raised : PropTypes.any,
underlayColor : PropTypes.any,
children : PropTypes.any,
type : PropTypes.string,
style : PropTypes.any,
activeOpacity : PropTypes.any,
onPress : PropTypes.string
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment