Advertisement
Guest User

Untitled

a guest
Aug 25th, 2019
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.87 KB | None | 0 0
  1. import { useRef } from 'react';
  2.  
  3. const useDoubleClick = (onClick, onDoubleClick, doubleClickTimeout = 300) => {
  4. const timeout = useRef(null);
  5.  
  6. const handleClick = () => {
  7. if (timeout.current !== null) {
  8. onDoubleClick();
  9. clearTimeout(timeout.current);
  10. timeout.current = null;
  11. } else {
  12. timeout.current = setTimeout(()=>{
  13. onClick();
  14. clearTimeout(timeout.current);
  15. timeout.current = null
  16. }, doubleClickTimeout);
  17. }
  18. };
  19.  
  20. return handleClick;
  21. };
  22.  
  23. export default useDoubleClick;
  24.  
  25. /*
  26. Usage:
  27.  
  28. import useDoubleClick from 'useDoubleClick';
  29.  
  30. const App => () => {
  31. const handleClick = useDoubleClick(() => console.log('click'), () => console.log('double click'), 500); // the third param is the double click timeout in ms, optional (default: 300ms)
  32. return (
  33. <div>
  34. <button onClick={handleClick}/>
  35. </div>
  36. );
  37. };
  38. */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement