rct-draggable

1.0.2 • Public • Published

A lightweight draggable component with render prop!

Install

npm install --save rct-draggable

Usage

This is a complete example with commentary demonstrating how you could create a reusable component that wraps children with a draggable div.

import React, { Component } from 'react'
import Draggable from 'rct-draggable'

const DraggableWrapper = (props) => (
  <Draggable {...props}>
    {({ position, events, setRef, isDragging }) => (
      <div
        // The ref is used to measure the element
        ref={setRef}
        // Spread the events on an element and it will act as a handle
        {...events}
        // The css classes used here change the cursor to a draggable/dragging hand or disabled
        className={`${isDragging ? 'dragging' : 'draggable'} ${props.disabled ? 'disabled' : ''}`}
        // Simple styles to make the component move
        style={{
          position: 'absolute',
          left: position.x,
          top: position.y
        }}
      >
        {props.children}
      </div>
    )}
  </Draggable>
)

class Example extends Component {
  render() {
    return (
      <DraggableWrapper>
        <div>This is now draggable</div>
      </DraggableWrapper>
    )
  }
}

Props

All props are optional

<Draggable
  // --- disable movement per axis
  x={false}
  y={false}
  // --- ignore user input
  disabled
  // --- make it a controlled component
  position={{x: 20, y: 20}
  // --- start at this position
  defaultPosition={{ x: 50, y: 50 }}
  // --- move on a grid... you can also pass just x or just y
  grid={{ x: 20, y: 20 }}
  // --- limit the movement...
  // --- you could use getBoundingClientRect() to constrain it to another element
  bounds={{ left: 0, top: 0, right: 300, bottom: 300 }}
  // --- self explanatory events
  onStart={(data)=>console.log(data)}
  onMove={(data)=>console.log(data)}
  onStop={(data)=>console.log(data)}
  >
  {/*...child function here...*/}
</Draggable>

License

MIT © spredemann

Readme

Keywords

none

Package Sidebar

Install

npm i rct-draggable

Weekly Downloads

0

Version

1.0.2

License

MIT

Unpacked Size

20.3 kB

Total Files

4

Last publish

Collaborators

  • gspredemann