index.html

React Add Event Listener to Component

Word count: 230Reading time: 1 min
2020/03/14 Share

Problem

When making a file drag and drop box as the example below, we need to add event listeners like dragenter drop to the HTML element.

Solution

The solution is to add the listeners to this.theAliasOfTheElement, and then bind the reference to the element in the render function.

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import React from "react";
import PropTypes from "prop-types";

const style = {
width: "100%",
height: "100%",
backgroundColor: "yellow",
textAlign: "center",
padding: 40,

};

export default class MyDragAndDrop extends React.PureComponent {

constructor(props) {
super(props);
}

componentDidMount() {
this.dropBox.addEventListener("dragenter", this.onDragEnter);
this.dropBox.addEventListener("dragleave", this.onDragleave);
this.dropBox.addEventListener("drop", this.onDrop);
this.dropBox.addEventListener("dragover", this.onDragOver);
}

componentWillUnmount() {
this.dropBox.removeEventListener("dragenter", this.onDragEnter);
this.dropBox.removeEventListener("dragleave", this.onDragleave);
this.dropBox.removeEventListener("drop", this.onDrop);
this.dropBox.removeEventListener("dragover", this.onDragOver);
}

onDragOver = event => {
event.stopPropagation();
event.preventDefault();
// console.log("dragOver");
return false;
};

onDragEnter = event => {
event.stopPropagation();
event.preventDefault();
console.debug("dragEnter");
return false;
};

onDragleave = event => {
event.stopPropagation();
event.preventDefault();
console.debug("dragLeft");
return false;
};

onDrop = event => {
event.stopPropagation();
event.preventDefault();
console.debug("drop");
return false;
};

render() {
return (
<div ref={elem => this.dropBox = elem} style={style}>
Drag and drop files here
</div>
);
}
}

Result

BEAUTIFUL! I should be a designer :)

EOF

CATALOG
  1. 1. Problem
  2. 2. Solution
  3. 3. Code
  4. 4. Result