0

I'm getting back into React and am wanting to have some components which can be dragged around by the user on the website I'm making. Note, by draggable I mean 'moved around the page by mouse', not the 'drag and drop' kind of draggable.

My code so far kind of works but is a bit jerky and does not always register when the mouse is up/released.

This is the component I'm trying to make draggable.

import React from 'react';

export default class Folder extends React.Component {

  constructor(props) {
    super(props);
    this.state = {mouseDown: false,
                    name: props.name, 
                    left: props.left,
                    top:props.top   
                 };
  } 

  // mouse down -> grab coords and offset
  // mouse move, if mouse down true, make mouse coords 
  // folder coords
  // on mouse up change mouse down to false.(can't move)

  mouseHandler(e){
    this.setState({mouseDown: true})
  }
  mouseMove(e){
    if(!this.state.mouseDown){
        return
    }else{
        console.log('mouse held and moving')
        let newLeft = e.clientX - e.nativeEvent.offsetX
        let newTop = e.clientY - e.nativeEvent.offsetY
        this.setState({left: newLeft, top:newTop})
    }
  }
  mouseUp(e){
    this.setState({mouseDown: false})
    console.log('mouse up')
  }



  render() {
    return  (<div className="icon" 
             onMouseDown={(e) => this.mouseHandler(e)}
             onMouseMove={(e) => this.mouseMove(e)}
             onMouseUp={(e) => this.mouseUp(e)}
             style={{top: this.state.top, left: this.state.left}} >
                <div className="tab"></div>
                <div className="foldergap"></div>
                <div className="foldertitle"><p>{this.state.name}</p>/div>
            </div>)
  }
};

I know there are libraries I could use but I would like to use my own work where I can. I have also seen this similar question but the answers either seemed to use outdated techniques, DOM manipulation (which doesn't seem like the 'React way') or libraries.

My question is what am I doing wrong and what is the recommended way of achieving this functionality?

Thank you.

Community
  • 1
  • 1
damtypo
  • 150
  • 1
  • 18
  • don't understand "drag around but not drag-n-drop", so what is drag around is for if you don't drop it somewhere? – Jeb50 Mar 23 '17 at 05:28
  • Sure. I want something like this for react : https://jqueryui.com/draggable/ NOT like this : https://www.w3schools.com/html/html5_draganddrop.asp They are clearly different in the look and effect but I have seen them both referred to as 'draggable' and I just wanted it to be obvious:) – damtypo Mar 23 '17 at 05:35

0 Answers0