Advertisement
Guest User

Untitled

a guest
Aug 18th, 2019
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.38 KB | None | 0 0
  1. /**
  2. `useDragToScroll` - this custom hook allow to change scroll position during element drag.
  3.  
  4. Usage example:
  5. const YourComponent = React.memo((props) => {
  6.  
  7. const [isBlocked, setIsBlocked] = useState(false);
  8.  
  9. const myRef = useRef();
  10.  
  11. const {
  12. mouseLeave,
  13. mouseMove,
  14. mouseUp,
  15. mouseDown,
  16. } = useDragToScroll(myRef, isBlocked);
  17.  
  18. return <div>Hello World</div>
  19. });
  20. */
  21.  
  22. import { useReducer } from 'react';
  23.  
  24. const useDragToScroll = (ref, isBlocked = false) => {
  25. const initialState = {
  26. startX: undefined,
  27. isDown: false,
  28. scrollLeft: undefined,
  29. };
  30.  
  31. const reducer = (state, newState) => ({ ...state, ...newState });
  32. const [state, setState] = useReducer(reducer, initialState);
  33.  
  34. const mouseLeave = () => setState({ isDown: false });
  35.  
  36. const mouseMove = e => {
  37. e.preventDefault();
  38. const { current } = ref;
  39. if (!state.isDown || isBlocked) return;
  40. const x = e.pageX - current.offsetLeft;
  41. const walk = (x - state.startX);
  42. current.scrollLeft = state.scrollLeft - walk;
  43. };
  44.  
  45. const mouseUp = () => setState({ isDown: false });
  46.  
  47. const mouseDown = e => {
  48. e.preventDefault();
  49. const { current } = ref;
  50. setState({
  51. isDown: true,
  52. startX: (e.pageX - current.offsetLeft),
  53. scrollLeft: current.scrollLeft,
  54. });
  55. };
  56.  
  57. return {
  58. mouseLeave,
  59. mouseMove,
  60. mouseUp,
  61. mouseDown,
  62. };
  63. };
  64.  
  65. export default useDragToScroll;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement