react-drag-to-select

A react library which adds drag to select to your app

Showing:

Popularity

Downloads/wk

393

GitHub Stars

10

Maintenance

Last Commit

4mos ago

Contributors

1

Package

Dependencies

0

License

MIT

Type Definitions

Tree-Shakeable

Yes?

Categories

Readme

react-drag-to-select

A react library which adds drag to select to your app

NPM JavaScript Style Guide

Install

npm install --save react-drag-to-select

Usage

Example


const App = () => {

  const handleSelectionChange = useCallback((box: Box) => {
    console.log(box);
  },[])

  const { DragSelection } = useSelectionContainer({
    onSelectionChange,
  });

  return (
    <div id='root'>
      <DragSelection/>
      <div>Selectable element</div>
    </div>
  )
}

  1. Add useSelectionContainer hook to your component and pass onSelectionChange handler
  2. Render <DragSelection/> somewhere in code
  3. That's it! Mouse selection will appear, when you click and drag within window or element passed in eventsElement.

This library will not select your items. You have to handle selection yourself in onSelectionChange method (see example). You can use boxesIntersects(boxA, boxB) method to check if element intersetcs with selection.

useSelectionContainer arguments

NameRequiredTypeDefaultDescription
onSelectionStartNo() => voidMethod called when selection starts (mouse is down and moved)
onSelectionEndNo() => voidMethod called when selection ends (mouse is up)
onSelectionChangeYes(box: Box) => voidMethod called when selection moves
isEnabledNobooleantrueIf false, selection does not fire
eventsElementNoWindow, HTMLElement or nullwindowElement to listen mouse events
selectionPropsNoReact.HTMLAttributesProps of selection - you can pass style here as shown below

Selection styling

To style your selection, pass selectionProps: { style } prop:

  const { DragSelection } = useSelectionContainer({
    ...,
    selectionProps: {
      style: {
        border: '2px dashed purple',
        borderRadius: 4,
        backgroundColor: 'brown',
        opacity: 0.5,
      },
    },
  });

The default style is

{
  border: '1px solid #4C85D8',
  background: 'rgba(155, 193, 239, 0.4)',
  position: `absolute`,
  zIndex: 99,
}

Working with draggable elements

If you use any drag-n-drop library (like react-dnd or react-beautiful-dnd), you may want to not start selection when user starts dragging an element. To prevent this, add data-draggable=true to your element - selection won't be started if user clicks and drags this element or its children:

<div data-draggable=true>
...
</div>

Used by

License

MIT © Air

Rate & Review

Great Documentation0
Easy to Use0
Performant0
Highly Customizable0
Bleeding Edge0
Responsive Maintainers0
Poor Documentation0
Hard to Use0
Slow0
Buggy0
Abandoned0
Unwelcoming Community0
100