Skip to content

Instantly share code, notes, and snippets.

@beerose
Created Nov 29, 2019
Embed
What would you like to do?
import * as React from 'react';
import { useState } from 'react';
export const useTouch = (ref: React.RefObject<HTMLElement>, defaultState = false) => {
const [state, setState] = useState(false);
React.useEffect(() => {
const element = ref.current;
if (!element) {
return;
}
const onTouchStart = () => setState(true);
const onTouchEnd = () => setState(false);
element.addEventListener('touchstart', onTouchStart);
element.addEventListener('touchend', onTouchEnd);
return () => {
element.removeEventListener('focus', onTouchStart);
element.removeEventListener('blur', onTouchEnd);
};
}, [ref]);
return state;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment