Skip to content

Instantly share code, notes, and snippets.

@sbin0819
Last active July 3, 2022 05:41
Show Gist options
  • Save sbin0819/1cd2b73d1d86ad93575bf359b7eb6239 to your computer and use it in GitHub Desktop.
Save sbin0819/1cd2b73d1d86ad93575bf359b7eb6239 to your computer and use it in GitHub Desktop.

plain js

document.getElementById('drag').ondragstart = function() {
  e.dataTransfer.setData('data', this.innerHTML); // 드래그해보세요 문자열 전달
};

document.getElementById('drop').ondragover = function(e) {
  e.preventDefault(); // 필수 이 부분이 없으면 ondrop 이벤트가 발생하지 않습니다.
};
document.getElementById('drop').ondrop = function() {
  alert(e.dataTransfer.getData('data')); // 데이터를 가져옵니다.
};
e.dataTransfer.setData
e.dataTransfer.getData

e.dataTransfer.items
e.dataTransfer.files

with react

const DragDrop = () => {
    const handleDragEnter = (e) => {
        e.preventDefault()
        e.stopPropagation()
        console.log('enter')
    }
    const handleDragLeave = (e) => {
        e.preventDefault()
        e.stopPropagation()
        console.log('leave')
    }
    const handleDragOver = (e) => {
        e.preventDefault()
        e.stopPropagation()
    }
    const handleDrop = (e) => {
        e.preventDefault()
        e.stopPropagation()
        console.log(e.dataTransfer.files)
    }
    return (
        <div
            className={'drag-drop-zone'}
            onDrop={(e) => handleDrop(e)}
            onDragOver={(e) => handleDragOver(e)}
            onDragEnter={(e) => handleDragEnter(e)}
            onDragLeave={(e) => handleDragLeave(e)}
        >
            <p>Drag files here to upload</p>
        </div>
    )
}

references

드래그 드롭 API
How To Use The HTML Drag-And-Drop APi In React

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment