make custom draggable in react

Solutions on MaxInterview for make custom draggable in react by the best coders in the world

showing results for - "make custom draggable in react"
Debora
26 Jul 2019
1var Draggable = React.createClass({
2  getDefaultProps: function () {
3    return {
4      // allow the initial position to be passed in as a prop
5      initialPos: {x: 0, y: 0}
6    }
7  },
8  getInitialState: function () {
9    return {
10      pos: this.props.initialPos,
11      dragging: false,
12      rel: null // position relative to the cursor
13    }
14  },
15  // we could get away with not having this (and just having the listeners on
16  // our div), but then the experience would be possibly be janky. If there's
17  // anything w/ a higher z-index that gets in the way, then you're toast,
18  // etc.
19  componentDidUpdate: function (props, state) {
20    if (this.state.dragging && !state.dragging) {
21      document.addEventListener('mousemove', this.onMouseMove)
22      document.addEventListener('mouseup', this.onMouseUp)
23    } else if (!this.state.dragging && state.dragging) {
24      document.removeEventListener('mousemove', this.onMouseMove)
25      document.removeEventListener('mouseup', this.onMouseUp)
26    }
27  },
28
29  // calculate relative position to the mouse and set dragging=true
30  onMouseDown: function (e) {
31    // only left mouse button
32    if (e.button !== 0) return
33    var pos = $(this.getDOMNode()).offset()
34    this.setState({
35      dragging: true,
36      rel: {
37        x: e.pageX - pos.left,
38        y: e.pageY - pos.top
39      }
40    })
41    e.stopPropagation()
42    e.preventDefault()
43  },
44  onMouseUp: function (e) {
45    this.setState({dragging: false})
46    e.stopPropagation()
47    e.preventDefault()
48  },
49  onMouseMove: function (e) {
50    if (!this.state.dragging) return
51    this.setState({
52      pos: {
53        x: e.pageX - this.state.rel.x,
54        y: e.pageY - this.state.rel.y
55      }
56    })
57    e.stopPropagation()
58    e.preventDefault()
59  },
60  render: function () {
61    // transferPropsTo will merge style & other props passed into our
62    // component to also be on the child DIV.
63    return this.transferPropsTo(React.DOM.div({
64      onMouseDown: this.onMouseDown,
65      style: {
66        left: this.state.pos.x + 'px',
67        top: this.state.pos.y + 'px'
68      }
69    }, this.props.children))
70  }
71})
72
similar questions
queries leading to this page
make custom draggable in react