Advertisement
ronikuchan

Reactjs Scroll Horizontal Move

Sep 30th, 2021
534
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.83 KB | None | 0 0
  1. const onMouseMove = e => {
  2.  
  3. const { isDown } = state
  4.  
  5. if (!isDown) { return }
  6. console.log('move')
  7. if (myRef && myRef.current && !myRef.current.contains(e.target)) {
  8. return
  9. }
  10. // console.log('mousemove')
  11.  
  12. e.preventDefault()
  13.  
  14. const {clientX, scrollX, isScrolling} = state
  15. const el = myRef.current
  16.  
  17. if (isScrolling) {
  18. el.scrollLeft = scrollX + e.clientX - clientX
  19. // myRef.curent.scrollLeft = scrollX + e.clientX - clientX
  20. let sX = scrollX + e.clientX - clientX
  21. let cX = e.clientX
  22.  
  23. setState({
  24. ...state,
  25. scrollX: sX,
  26. clientX: cX
  27. })
  28. }
  29.  
  30. }
  31.  
  32. const onMouseUp = e => {
  33. console.log('mouseup', e)
  34. if (myRef && myRef.current && !myRef.current.contains(e.target)) {
  35. return
  36. }
  37.  
  38. e.preventDefault()
  39.  
  40. setState({
  41. ...state,
  42. isScrolling: false,
  43. })
  44. }
  45.  
  46. const onMouseDown = e => {
  47. console.log('mousedown', e)
  48. if (myRef && myRef.current && !myRef.current.contains(e.target)) {
  49. return
  50. }
  51.  
  52. e.preventDefault()
  53.  
  54. setState({
  55. ...state,
  56. isScrolling: true,
  57. clientX: e.clientX
  58. })
  59. }
  60.  
  61. useEffect(() => {
  62. document.addEventListener('mousedown', onMouseDown)
  63. document.addEventListener('mouseup', onMouseUp)
  64. document.addEventListener('mousemove', onMouseMove)
  65.  
  66. return () => {
  67. document.removeEventListener('mousedown', onMouseDown)
  68. document.removeEventListener('mouseup', onMouseUp)
  69. document.removeEventListener('mousemove', onMouseMove)
  70. }
  71. })
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement