Git Product home page Git Product logo

react-draggable's Introduction

React-Draggable

TravisCI Build Status Appveyor Build Status npm downloads gzip size version

A simple component for making elements draggable.

<Draggable>
  <div>I can now be moved around!</div>
</Draggable>
Version Compatibility
4.x React 16.3+
3.x React 15-16
2.x React 0.14 - 15
1.x React 0.13 - 0.14
0.x React 0.10 - 0.13

Technical Documentation

Installing

$ npm install react-draggable

If you aren't using browserify/webpack, a UMD version of react-draggable is available. It is updated per-release only. This bundle is also what is loaded when installing from npm. It expects external React and ReactDOM.

If you want a UMD version of the latest master revision, you can generate it yourself from master by cloning this repository and running $ make. This will create umd dist files in the dist/ folder.

Exports

The default export is <Draggable>. At the .DraggableCore property is <DraggableCore>. Here's how to use it:

// ES6
import Draggable from 'react-draggable'; // The default
import {DraggableCore} from 'react-draggable'; // <DraggableCore>
import Draggable, {DraggableCore} from 'react-draggable'; // Both at the same time

// CommonJS
let Draggable = require('react-draggable');
let DraggableCore = Draggable.DraggableCore;

<Draggable>

A <Draggable> element wraps an existing element and extends it with new event handlers and styles. It does not create a wrapper element in the DOM.

Draggable items are moved using CSS Transforms. This allows items to be dragged regardless of their current positioning (relative, absolute, or static). Elements can also be moved between drags without incident.

If the item you are dragging already has a CSS Transform applied, it will be overwritten by <Draggable>. Use an intermediate wrapper (<Draggable><span>...</span></Draggable>) in this case.

Draggable Usage

View the Demo and its source for more.

import React from 'react';
import ReactDOM from 'react-dom';
import Draggable from 'react-draggable';

class App extends React.Component {

  eventLogger = (e: MouseEvent, data: Object) => {
    console.log('Event: ', e);
    console.log('Data: ', data);
  };

  render() {
    return (
      <Draggable
        axis="x"
        handle=".handle"
        defaultPosition={{x: 0, y: 0}}
        position={null}
        grid={[25, 25]}
        scale={1}
        onStart={this.handleStart}
        onDrag={this.handleDrag}
        onStop={this.handleStop}>
        <div>
          <div className="handle">Drag from here</div>
          <div>This readme is really dragging on...</div>
        </div>
      </Draggable>
    );
  }
}

ReactDOM.render(<App/>, document.body);

Draggable API

The <Draggable/> component transparently adds draggability to its children.

Note: Only a single child is allowed or an Error will be thrown.

For the <Draggable/> component to correctly attach itself to its child, the child element must provide support for the following props:

  • style is used to give the transform css to the child.
  • className is used to apply the proper classes to the object being dragged.
  • onMouseDown, onMouseUp, onTouchStart, and onTouchEnd are used to keep track of dragging state.

React.DOM elements support the above properties by default, so you may use those elements as children without any changes. If you wish to use a React component you created, you'll need to be sure to transfer prop.

<Draggable> Props:

//
// Types:
//
type DraggableEventHandler = (e: Event, data: DraggableData) => void | false;
type DraggableData = {
  node: HTMLElement,
  // lastX + deltaX === x
  x: number, y: number,
  deltaX: number, deltaY: number,
  lastX: number, lastY: number
};

//
// Props:
//
{
// If set to `true`, will allow dragging on non left-button clicks.
allowAnyClick: boolean,

// Determines which axis the draggable can move. This only affects
// flushing to the DOM. Callbacks will still include all values.
// Accepted values:
// - `both` allows movement horizontally and vertically (default).
// - `x` limits movement to horizontal axis.
// - `y` limits movement to vertical axis.
// - 'none' stops all movement.
axis: string,

// Specifies movement boundaries. Accepted values:
// - `parent` restricts movement within the node's offsetParent
//    (nearest node with position relative or absolute), or
// - a selector, restricts movement within the targeted node
// - An object with `left, top, right, and bottom` properties.
//   These indicate how far in each direction the draggable
//   can be moved.
bounds: {left?: number, top?: number, right?: number, bottom?: number} | string,

// Specifies a selector to be used to prevent drag initialization. The string is passed to
// Element.matches, so it's possible to use multiple selectors like `.first, .second`.
// Example: '.body'
cancel: string,

// Class names for draggable UI.
// Default to 'react-draggable', 'react-draggable-dragging', and 'react-draggable-dragged'
defaultClassName: string,
defaultClassNameDragging: string,
defaultClassNameDragged: string,

// Specifies the `x` and `y` that the dragged item should start at.
// This is generally not necessary to use (you can use absolute or relative
// positioning of the child directly), but can be helpful for uniformity in
// your callbacks and with css transforms.
defaultPosition: {x: number, y: number},

// If true, will not call any drag handlers.
disabled: boolean,

// Specifies the x and y that dragging should snap to.
grid: [number, number],

// Specifies a selector to be used as the handle that initiates drag.
// Example: '.handle'
handle: string,

// If desired, you can provide your own offsetParent for drag calculations.
// By default, we use the Draggable's offsetParent. This can be useful for elements
// with odd display types or floats.
offsetParent: HTMLElement,

// Called whenever the user mouses down. Called regardless of handle or
// disabled status.
onMouseDown: (e: MouseEvent) => void,

// Called when dragging starts. If `false` is returned any handler,
// the action will cancel.
onStart: DraggableEventHandler,

// Called while dragging.
onDrag: DraggableEventHandler,

// Called when dragging stops.
onStop: DraggableEventHandler,

// If running in React Strict mode, ReactDOM.findDOMNode() is deprecated.
// Unfortunately, in order for <Draggable> to work properly, we need raw access
// to the underlying DOM node. If you want to avoid the warning, pass a `nodeRef`
// as in this example:
//
// function MyComponent() {
//   const nodeRef = React.useRef(null);
//   return (
//     <Draggable nodeRef={nodeRef}>
//       <div ref={nodeRef}>Example Target</div>
//     </Draggable>
//   );
// }
//
// This can be used for arbitrarily nested components, so long as the ref ends up
// pointing to the actual child DOM node and not a custom component.
//
// For rich components, you need to both forward the ref *and props* to the underlying DOM
// element. Props must be forwarded so that DOM event handlers can be attached. 
// For example:
//
//   const Component1 = React.forwardRef(function (props, ref) {
//     return <div {...props} ref={ref}>Nested component</div>;
//   });
//
//   const nodeRef = React.useRef(null);
//   <DraggableCore onDrag={onDrag} nodeRef={nodeRef}>
//     <Component1 ref={nodeRef} />
//   </DraggableCore>
//
// Thanks to react-transition-group for the inspiration.
//
// `nodeRef` is also available on <DraggableCore>.
nodeRef: React.Ref<typeof React.Component>,

// Much like React form elements, if this property is present, the item
// becomes 'controlled' and is not responsive to user input. Use `position`
// if you need to have direct control of the element.
position: {x: number, y: number}

// A position offset to start with. Useful for giving an initial position
// to the element. Differs from `defaultPosition` in that it does not
// affect the position returned in draggable callbacks, and in that it
// accepts strings, like `{x: '10%', y: '10%'}`.
positionOffset: {x: number | string, y: number | string},

// Specifies the scale of the canvas your are dragging this element on. This allows
// you to, for example, get the correct drag deltas while you are zoomed in or out via
// a transform or matrix in the parent of this element.
scale: number
}

Note that sending className, style, or transform as properties will error - set them on the child element directly.

Controlled vs. Uncontrolled

<Draggable> is a 'batteries-included' component that manages its own state. If you want to completely control the lifecycle of the component, use <DraggableCore>.

For some users, they may want the nice state management that <Draggable> provides, but occasionally want to programmatically reposition their components. <Draggable> allows this customization via a system that is similar to how React handles form components.

If the prop position: {x: number, y: number} is defined, the <Draggable> will ignore its internal state and use the provided position instead. Alternatively, you can seed the position using defaultPosition. Technically, since <Draggable> works only on position deltas, you could also seed the initial position using CSS top/left.

We make one modification to the React philosophy here - we still allow dragging while a component is controlled. We then expect you to use at least an onDrag or onStop handler to synchronize state.

To disable dragging while controlled, send the prop disabled={true} - at this point the <Draggable> will operate like a completely static component.

<DraggableCore>

For users that require absolute control, a <DraggableCore> element is available. This is useful as an abstraction over touch and mouse events, but with full control. <DraggableCore> has no internal state.

See React-Resizable and React-Grid-Layout for some usage examples.

<DraggableCore> is a useful building block for other libraries that simply want to abstract browser-specific quirks and receive callbacks when a user attempts to move an element. It does not set styles or transforms on itself and thus must have callbacks attached to be useful.

DraggableCore API

<DraggableCore> takes a limited subset of options:

{
  allowAnyClick: boolean,
  cancel: string,
  disabled: boolean,
  enableUserSelectHack: boolean,
  offsetParent: HTMLElement,
  grid: [number, number],
  handle: string,
  onStart: DraggableEventHandler,
  onDrag: DraggableEventHandler,
  onStop: DraggableEventHandler,
  onMouseDown: (e: MouseEvent) => void,
  scale: number
}

Note that there is no start position. <DraggableCore> simply calls drag handlers with the below parameters, indicating its position (as inferred from the underlying MouseEvent) and deltas. It is up to the parent to set actual positions on <DraggableCore>.

Drag callbacks (onStart, onDrag, onStop) are called with the same arguments as <Draggable>.


Contributing

  • Fork the project
  • Run the project in development mode: $ npm run dev
  • Make changes.
  • Add appropriate tests
  • $ npm test
  • If tests don't pass, make them pass.
  • Update README with appropriate docs.
  • Commit and PR

Release checklist

  • Update CHANGELOG
  • make release-patch, make release-minor, or make-release-major
  • make publish

License

MIT

react-draggable's People

Contributors

acusti avatar andrewraycode avatar billcz avatar brianfay avatar cjblomqvist avatar davidstubbs avatar davidwells avatar dependabot[bot] avatar erfangc avatar gargroh avatar ipiranhaa avatar jmuerle avatar latentflip avatar liseki avatar martinross avatar matiss avatar mzabriskie avatar ndelangen avatar nikolas avatar panzarino avatar prayagverma avatar quolpr avatar sebastiaannijland avatar strml avatar tnrich avatar trysound avatar varad25 avatar victor-homyakov avatar williamstein avatar wojtekmaj avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

react-draggable's Issues

Percentage based drag system

I'm trying to create resizable split panes. If a draggable component (the handle between panes) is set to a % offset from its parent, it's much more convenient. I'm not sure I can fanangle it with a transform: translate setup

ie11 support

Hi, is IE11 supported with react-draggable? I couldn't get the demo page to work when using IE11 on a windows 7 vm so I'm not sure if the demo page is just pointing to old code or if this is a general issue with react-draggable.

When dragging I saw "SCRIPT5007: Unable to get property '0' of undefined or null reference File: react-draggable.min.js, Line: 1, Column: 1805"

Does not play well with touch and mouse events.

If you are using your mouse on a touch screen laptop the mouse events will not work. I've fixed this locally but want to wait until my other PR is pulled in before I put in another pull request.

Move element from javascript

Hi! Is there anyway to move the draggable element without touch them? I'm trying to move to position I click.

Thanks!

var root is undefined

var root = typeof window !== 'undefined' ? window : this; in draggable.js line 7

For some reason this is returning undefined for my setup. Things seem to work if I assign a new object {} instead. Is there any reason this has to be used?

Please, use translate3d instead of translate

I'm using this on a mobile app, translate is very slow as it don't make use of the GPU, you can just make a 3d option available, I'm forking it just for this. This is a great plugin, it will fit my needs with this option.

Still drags if mouse let go away from draggable

If I mousedown on the horizontal or vertical draggables and move the mouse off the box then mouseup, the draggable behaves as though I still have mousedown until I mouseup on the box itself. Probably not desired behavior. Perhaps putting an event listener on the body for mouseups after the mousedown would be a fix? Can't wait until I actually know react and can PR for you...

Multitouch support?

This may be a bit of a pipedream, but it would be great to support multi-touch devices by allowing multiple elements to be dragged simultaneously.

Right now, when you try to drag two elements at the same time, one touchmove event seems to take over for both elements.

From what I can tell, this happens because event listeners for move events are attached to the document, rather than a specific element. This means that "handleDrag" is going to fire on any component that is currently dragging.

I tried hacking together a solution with this in handleDrag:
if(e.target != React.findDOMNode(this)){console.log(e.target); return;}

I also had to change getControlPosition to look for "targetTouches" instead of "touches"
var position = (e.targetTouches && e.targetTouches[0]) || e;

This does allow elements to be moved independently via touch, but unfortunately causes another issue. If you drag too quickly, you're out of the bounds of the element, so the move event doesn't fire and control of the element is lost.

So I guess the event listeners need to stay on the document. Maybe an alternative solution would be keeping track of which touch in the e.touches array corresponds to which component. That seems tricky, but if I can come up with a clean way to do it I'll put in a pull request.

demo not working?

The demo is not working for me on chrome?

Uncaught TypeError: Cannot read property '0' of undefined react-draggable.js:146 getControlPosition react-draggable.js:146 module.exports.React.createClass.handleDragStart react-draggable.js:417 boundMethod 10540963_267651446772964_1656155574_n.js:7071 ....

droppable example

I am wondering how this draggable component actually can be used. I would think that usual use case is to drag & drop. But I struggle to see how I could use it for drag&drop.

Is anyone here using it for drag&drop? It would be very helpful to see example.

Thank you!

Feature Request: "disabled" prop

Sometimes you want to wrap elements in a <Draggable/> definition but not have them draggable until some condition is met. Currently you have to do this via:

if (shouldBeDraggable) {
    return (
        <Draggable>
            <div />
        </Draggable>
    );
} else {
    return (
        <div/>
    );
}

This is highly verbose and requires handling of different children prop values. If would be nice if react-draggable supported a disabled prop which would allow me to do something like this:


return (
    <Draggable disabled={!shouldBeDraggable}>
        <div />
    </Draggable>
);

Have build in repo

As a windows user, there are complications getting the repo to build, which is really unfortunate because I really just wanted to get the compiled webpack file. It would be lovely if the repo consisted (at least with every release) had a build dir with the webpack (and any other files builded).

Should be very easy to achieve. Looks like a great component for React btw!

component not updating on props change

I'm having issues with Draggable not re-rendering/repositioning on the page when the start data changes.

//... 
render: function() {
    var x = this.props.x;
    if (!x) x = 200;
    return this.transferPropsTo(
      <Draggable
        grid={[100, zoom/2]}
        start={{x: x, y: this.props.start * zoom}}
        onDrag={this.handleDrag}
        onStop={this.handleStop}
        zIndex={10000 + this.props.index * 10}
        handle=".start"
      >
      <section className="segment no-cursor" key={this.props.key} >....</section>
  </Draggable>

when this.props.x or this.props.start changes, the Draggable wont move to the new coordinates; Is there a way to force re-render or to tell it things change as desired position?

Add threshold

I would like to be able to not trigger onStart unless the user has dragged more than 20 pixels (this should be configurable).

Does not work in react .13

In 0.13 I receive the error. Likely due to depreciation of renderComponent

"Cannot read property '__reactAutoBindMap' of null

Parent boundaries are offset when element is added after load

I just want to say that react-draggable is very useful and easy to use. However, I have an issue when I use bounds="parent" and then add an element in after page load: the border for the parent is offset to the very top left corner of the page.

Demonstration: Dragging problem

Dragging SVG elements in IE (any version)

At the moment I don't have a jsfiddle setup, but it appears that the dragging of SVG elements has no effect in any version of Internet Explorer. I can't think of any obvious reason why this would be because translate works just fine in IE on SVG. It seems to have something to do with the onDrag event listeners.

dragging on ios

When dragging on ios the browser continues to scroll. This behavior is visible on the demo page. Is there a way to disable scroll on touch start for mobile?

onStart should be when dragging starts

For Example

You have a contentEditable div that you can edit and drag. When dragging starts, you change contentEditable to false, when dragging stops you change contentEditable to true. However, at the moment onStart triggers on a single click, which means you can never click into a contentEditable div to edit it after you have dragged it.

onStart should trigger when the user has started to drag the element, in my opinion. Or a new function like onDragStart.

Draggable Iframes

Hi just wondering what is the best way to make an Iframe draggable?

It Doesn't Work With Images

var Floorplan = React.createClass({

  render: function() {
    var allBoothKeys = Object.keys(this.props.booths)
      , self = this
      , booths

    if (allBoothKeys.length < 1) return null

    booths = allBoothKeys.map(function(key) {
      return (<Booth key={key} booth={self.props.booths[key]} />)
    })

    return (
      <Draggable
        start={{ x: 0, y: 0 }}
      >
        <div>
          {booths}
        </div>
      </Draggable>
    )
  }
})

Works. But if, inside div, I add

<img id="layout" src="img/layout.png" />

Does something weird: the drag starts on mouse up and I have to click again to stop the drag.

moveOnStartChange causes unnecessary state updates

I'm using react-draggable in my application to scroll an item in a viewport (i.e. dragging the background scrolls the view), and also for custom scrollbars around the viewport. Needless to say, I needed to use the moveOnStartChange attribute to keep these two manners of scrolling the same viewport consistent. I found, however, that there was some really buggy behavior in react-draggable, and it stemmed from the fact that componentWillReceiveProps triggers too often.

If you declare your component like this:

<Draggable start={{x: 0, y: 0}}>...</Draggable>

then every time the render() method is called, the componentWillReceiveProps method is called because, technically, a new object is being passed as the 'start' property.

The solution I have come up with is to change lines 471-473 in the componentWillReceiveProps method to:

if (newProps.moveOnStartChange && newProps.start &&
    (newProps.start.x !== this.props.start.x || newProps.start.y !== this.props.start.y))
{
    this.setState(this.getInitialState(newProps));
}

Thoughts?

Ractify missing from dependencies

First of all, thanks for your work on the component.
When using the component with browserify it complains about reactify not being installed. Adding it to the package.json dependencies should fix that?

Detecting click vs drag

I have a use-case in which the draggable element can either be dragged around or clicked to begin editing. Is there a way to detect a single click versus a drag motion?

Programmatically trigger a drag start?

Is it possible to make a draggable component start following the mouse on, say, a button click? I'm imagining that a click, which would obviously contain a mouseup event, would be how the item got placed in this case.

Make react-draggable work with React Bootstrap Modal

Is there a way to make react-draggable work React Bootstrap Modal?

I'm thinking at something like this (btw..this doesn't work):

<Draggable handle=".modal-header">
    <Modal className="myClass" {...this.props} bsSize='small' title='Modal heading' animation={false}>
        <div className='modal-body'>
            <span>This is a test!</span>
        </div>
        <div className='modal-footer'>
            <Button>Close</Button>
        </div>
    </Modal>
</Draggable>

Inaccuracy within a svg

I'm not sure if this is within the scope of this project but I'm finding that if you make an element within a SVG draggable, the numbers are a bit inaccurate. This causes for quirky behavior when using a bound.

For example, try to move this rect quickly from left to right. You'll find it difficult to get it to line up with the dotted line it starts out on. It only works when you move slowly and smoothly. Initially, I was thinking it had something to do with pointer-events, but after playing around with it I'm not so sure.

http://jsfiddle.net/dzrgnjgf/15/

screen shot 2015-05-18 at 11 07 40 am

Update:

This seems to be webkit related as it's only happening within safari and chrome. Not firefox.

Have draggable start at default

Is there any way to have the drag start at the div's original value? for instance my css has the div's bottom : 0px. But once I wrap it in a draggable it ends up centered vertically.

Thanks!

Drag happens in webkit on drop down select

When a draggable component contains a drop down and a drop down option is changed with mouse, the components is moved when it should not be as opening selecting a new option and closing a drop down should not move the components.

Make react-draggable agnostic of the HTML structure position

This is related to #56

Let's have a look at the ReactBootstrap and Bootstrap Modals side by side. I have updated the repository to include a Bootstrap example also https://github.com/cosminnicula/ReactBootstrapModalDraggable

1.Bootstrap -> this works

<Draggable handle=".modal-header">
    <div className="modal">
        <div className="modal-dialog">
            <div className="modal-content">
                <div className="modal-header">
                ...
                </div>
            </div>
        </div>
</Draggable>

2.ReactBootstrap -> this does not work

<Draggable handle=".modal-header">
    <Modal>
        ...
    </Modal>
</Draggable>

Under the hood, <Modal /> generates the same HTML mark-up as 1.

Questions:
a) Since 2. is equivalent to 1. in terms of HTML mark-up, why <Dragglable /> would not work with 2. ? (not asking technical details, but rather as a client of the library)
b) If <Draggable /> wants to cover more use cases, it has to be more flexible in terms where in the HTML structure needs to be included. E.g. if ReactBootstrap, or any other component decides not to expose a renderer function or a custom component, then <Draggable /> cannot be used. A solution would be for <Draggable /> to be agnostic of the HTML structure position and rely only on the handle property. Is this make sense?

Would ❤️ to see these two questions addressed!

onDrag reports previous position

onDrag is called before updating the state. It therefore reports positions which correspond to the previous mouse event. I am trying to update the position of a sibling in the onDrag handler. This behavior causes the sibling to "lag" behind.

Even worse, since handleDragEnd resets the state before calling onStop, the last position is never reported. This could lead to persisting different a position than last displayed.

I could think of three possible solutions:

  • Set state before invoking onDrag. This would result in an extra render even if dragging is canceled. Not sure if this could have unwanted side effects.
  • Explicitly pass the new position to createUIEvent and make it fall back to state if non is passed.
  • Add a new event callback (onDragged?) to keep everything 100% backwards compatible. I can't help but feel that would be ugly, though.

I'd be happy to provide a PR.

Invariant Violation: exports.render(): A valid ReactComponent must be returned.

Hey,

when I use <Draggable>...</Draggable>, I get the following error:

Error: Invariant Violation: exports.render(): A valid ReactComponent must be returned. 
You may have returned undefined, an array or some other invalid object.

My code looks like this:

var React     = require('react'),
    Draggable = require('react-draggable');

module.exports = React.createClass({
  handleStart: function() {
    console.log('Dragging started');
  },

  handleDrag: function() {
    console.log('Dragged');
  },

  handleStop: function() {
    cosole.log('Draggins stopped');
  },

  render: function() {
    return (
      <Draggable
        onStart={this.handleStart}
        onDrag={this.handleDrag}
        onStop={this.handleStop}>
        <div className="foo">Bar</div>
      </Draggable>
    );
  }
));

When I remove the Draggable-stuff, the error disappears.

I logged the output of render() and got back a valid object.

draggable within another draggable

I have a use case where one draggable can be within another draggable and so on. I have positioned the elements as 'absolute'. When i move a child draggable element, the parents left+top are also changed and it moves too. I have also tried attaching handles for each element (by class name), but to no affect. Is it possible to move the child element independently?

Options for alternate drag offset strategies

This is similar to #81. I'm using draggable in an SVG context, and using translate() actually gets in the way, using x and y attrs would be better. In my specific case I can pan and zoom my canvas, as well as drag the elements on it. Getting element positions is now more complicated because there's the transform matrix applied to the top level node, and a second transform applied to the dragged item itself. This makes it harder to reason about the application and harder to do math to find local vs world coords, etc. If I could drag using x and y which works in SVG (or specify any other offset strategy) I would have a much easier time

Not Draggable when using in webpack starter

I haven't been able to figure out what the issue is. It could definitely be user related. The example works fine, but when I add react-draggable to package.json and install it, a non-draggable element is the result. It looks just like the example, but the dragging events don't occur. I tried this in another starter that had a build system and saw the same problem. I'm new with using webpack, so I assume there is something going on with the build that is messing things up.

This is the webpack starter I was using: https://github.com/webpack/react-starter

I changed index.jsx to look like the following:

/** @jsx React.DOM */

var React = require("react"),
    Draggable = require("react-draggable");

var Display = require("./Display");
var Control = require("./Control");

var Example = React.createClass({

    handleDrag: function(el, ui) {
        console.log(ui.position);
    },

    render: function() {
        require("./style.less");
        return (
            <div>
        <div className="module-example">
            <Display />
            <div>
                <Control action="increment" label="+1" />
                <Control action="decrement" label="-1" />
                <Control action="reset" label="Reset" />
            </div>
        </div>
          <Draggable grid={[25,25]} zIndex={100} onDrag={this.handleDrag}>
            <div className="box">I can be dragged anywhere</div>
          </Draggable>
        </div>
        );
    }
});
module.exports = Example;

Here is what the debug window looks like:
image

Request for enhancement, initial position.

I'm able to set the initial Draggable child component's position using a style absolute positioning. The Draggable component will then make translate transforms based off this initial position. The issue with this approach is that I'm unable to store the updated position directly.

Would it be possible to add a start prop to the Draggable component to set the initial position? I've attempted to set the child transform style on first render, but the Draggable component is not aware of this.

Here's a link to how I'm currently fleshing out a window system using your component.
https://github.com/nirrius/nirrius/blob/master/app/common/pane/index.jsx#L55-L69
http://nirri.us/~teffen

Thank you.

Multi-touch support

Try dragging two elements at once on a touch screen device. It doesn't work right. The second element starts moving, but its movement is correlated with the first element instead of moving on its own with the second finger.

Use the library without npm install.

Hi.
First: Thanks for your work, this is a great library.

My question: I enhanced my local fork (see #9) and would like to try it on my project. Because of my changes I can’t use the npm-install version of react-draggable. I am new to React and friends and am stuck getting draggable into my project. I tried to include the draggable.js and the main.js the traditional way. The actual error message is Uncaught ReferenceError: require is not defined caused by this line var React = require('react/addons');.
Any idea on how I can proceed?

Not working on React component

Hi !
I am trying to use react-draggable on dynamic children, ie:

var MyElem = require('MyElem.react')

this.state.elem.map(function(elem, i){
  return (
    <Draggable key=i> 
      <MyElem myModel={elem} />   
    </Draggable>
  )
}

the node is properly rendered but neither the events nor the the class "react-draggable" are added.

It works with static children like :

<Draggable>
    <p>drag me </p>
</Draggable>

I am using react with addons v0.13.3

Kind regards

moveOnStartChange breaks drag position

Check out the associated PR and open example/index.html. All it does is add moveOnStartChange to one drag element.

broken

You can see when you start dragging it the element jumps about 400 pixels down the page, not at the mouse coords, which I think is related to improperly handling/reading clientX and clientY. I was trying to implement a custom drag strategy to deal with my flux flow but it seems it's currently impossible because moveOnStartChange breaks dragging behavior.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.