React draggable example

draggable example in react with update state

by Hanu Pompiliu

HTML

<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.1.0/lodash.min.js"></script>
<div id="app"></div>

CSS

body{
      color: red;
      font-family: Helvetica, sans-serif;
      font-size: 20px;
    }
    #list{
      max-width: 500px;
      margin: 0;
      padding: 0;
      position: absolute;
    }
    li{
      padding: 10px;
      margin: 0 0 10px;
      cursor: move;
      list-style: none;
      border-radius: 3px;
    }
    li[data-id="a"]{
      background-color: #F44336;
    }
    li[data-id="b"]{
      background-color: #2196F3;
    }
    li[data-id="c"]{
      background-color: #009688;
    }
    .ui-sortable-placeholder{
      visibility: visible !important;
      border: 2px dashed #000;
    }

React

class SortableList extends React.Component {

constructor(props) {
    super(props);
    this.state = {
      items: [{
        id: 'a',
        position: 0,
        content: 'Adam'
      }, {
        id: 'b',
        position: 1,
        content: 'Betty'
      }, {
        id: 'c',
        position: 2,
        content: 'Charlie'
      }],
      left: 100,
      top: 100,
      key: 1
    };
  }

  componentDidMount() {
    $(ReactDOM.findDOMNode(this)).draggable({
      drag: (event,ui) => this.handleDraggableDrag(event,ui)
    });
  }
  
  
  shouldComponentUpdate(nextProps, nextState){
    return false;
  }
  
  
  componentDidUpdate(){
  $(ReactDOM.findDOMNode(this)).draggable({
      drag: (event,ui) => this.handleDraggableDrag(event,ui)
    });
  }
  
  handleDraggableDrag(event, ui){ 
  console.log(ui.position)
    		this.setState(ui.position)
  }

  handleSortableUpdate() {
    var newItems = _.clone(this.state.items, true);
    var $node = $(ReactDOM.findDOMNode(this));
    var ids = $node.sortable('toArray', { attribute: 'data-id' });
     console.log($node);

    ids.forEach((id, index) => {
      var item = _.findWhere(newItems, {id: id});
      item.position = index;
    });

    // Lets React reorder the DOM
    //$node.sortable('cancel');
    this.setState({ items: newItems });
  }
  
  moveToHandler(){
  	this.setState({
      left: 10,
      top: 10,
      key: Math.random()
      })
      this.forceUpdate();	
  }
  
  moveToHandler1(){
  	this.setState({
      left: 50,
      top: 50,
      key: Math.random()
      })
      this.forceUpdate();	
  }

  sortedItems(){
    var items = _.sortBy(this.state.items, 'position');

    return items.map((item) => {
      return (
        <li key={item.id} data-id={item.id} style={{backgroundColor:this.getRandomColor()}}>
          <strong>{item.content}</strong>
          <br/>
          id: {item.id} &bull; position: {item.position}
        </li>
      )
    })
  }
  
  getRandomColor() {
    var letters...