Sedana Yoga
Sedana Yoga

Reputation: 43

How to make a Draggable Div on React with nested event?

I want to make a draggable modal from scratch. Found this tutorial on youtube but it's still using static HTML and vanilla javascript. Tried to use useRef & useEffect on React but I found when clicking the element that using onDrag event inside onMouseDown will only trigger onMouseDown.

The code in vanilla javascript

header.addEventListener("mousedown", () => {
   header.classList.add("active");
   header.addEventListener("mousemove", onDrag);
});

Code in React

import React, { useRef, useEffect } from 'react'
import ReactDOM from 'react-dom'
import { ModalStyled } from './ModalComponentStyled'
import { ReactComponent as DragIconSVG } from '../../images/drag-icon.svg'

const modalRoot = document.getElementById('modal')

const ModalComponent = ({ close, children, zIndexProps }) => {
let modalWrapper = undefined
  const modalRef = useRef()
  const moveRef = useRef()
  useEffect(() => {
    modalWrapper = window.getComputedStyle(modalRef.current)
  }, [modalRef])

  const dragModalHandler = (e) => {
    // const left = parseInt(modalWrapper.left)
    // const top = parseInt(modalWrapper.top)
    // modalRef.current.style.left = `${left + movementX}px`
    // modalRef.current.style.top = `${top + movementY}px`

    console.log(e)
  }

  const mouseDownModalHandler = (e) => {
    dragModalHandler(e)
  }
return ReactDOM.createPortal(
    <ModalStyled zIndexProps={zIndexProps}>
      <div className="overlay" onClick={close}></div>
      <div ref={modalRef} className="modal-container">
        <div className="modal-children">
          {children}
          <div
            className="drag"
            ref={moveRef}
            onMouseDown={mouseDownModalHandler}
            onDrag={dragModalHandler}
          >
            <DragIconSVG />
          </div>
        </div>
      </div>
    </ModalStyled>,
    modalRoot
  )

I've converted the static vanilla code to sandbox so you guys can see clearly about my context. https://codesandbox.io/s/draggablediv-pm33s

Upvotes: 1

Views: 2753

Answers (1)

Sedana Yoga
Sedana Yoga

Reputation: 43

Got this solution using useState only https://codesandbox.io/s/draggablemodalreact-7gp38

Upvotes: 1

Related Questions