dnd-multi-backend

React DnD Multi Backend NPM Version dependencies Status devDependencies Status

Try it here!

This project is a Drag’n’Drop backend compatible with React DnD. It enables your application to use different DnD backends depending on the situation. You can either generate your own backend pipeline or use the default one (see rdndmb-html5-to-touch).

rdndmb-html5-to-touch starts by using the React DnD HTML5 Backend, but switches to the React DnD Touch Backend if a touch event is triggered. You application can smoothly use the nice HTML5 compatible backend and fallback on the Touch one on mobile devices!

Moreover, because some backends don’t support preview, a Preview component has been added to make it easier to mock the Drag’n’Drop “ghost”.

See the migration section for instructions when switching from 2.x.x, 3.x.x, 4.x.x, 5.0.x or 6.x.x.

Installation

npm install -S react-dnd-multi-backend

You can then import the backend using import { MultiBackend } from 'react-dnd-multi-backend'.

Backends pipeline

In order to use rdndmb-html5-to-touch, you will now need to install it separately:

npm install -S rdndmb-html5-to-touch

Usage

DndProvider (new API)

You can use the DndProvider component the same way you do the one from react-dnd (docs for more information), at the difference that you don’t need to specify backend as a prop, it is implied to be MultiBackend.

You must pass a ‘pipeline’ to use as argument. rdndmb-html5-to-touch is provided as another package but you can also write your own.

import { DndProvider } from 'react-dnd-multi-backend'
import { HTML5toTouch } from 'rdndmb-html5-to-touch' // or any other pipeline

const App = () => {
  return (
    <DndProvider options={HTML5toTouch}>
      <Example />
    </DndProvider>
  )
}

Backend (old API)

You can plug this backend in the DragDropContext the same way you do for any backend (e.g. ReactDnDHTML5Backend), you can see the docs for more information.

You must pass a ‘pipeline’ to use as argument. rdndmb-html5-to-touch is provided as another package but you can also write your own.

import { DndProvider } from 'react-dnd'
import { MultiBackend } from 'react-dnd-multi-backend'
import { HTML5toTouch } from 'rdndmb-html5-to-touch' // or any other pipeline

const App = () => {
  return (
    <DndProvider backend={MultiBackend} options={HTML5toTouch}>
      <Example />
    </DndProvider>
  )
}

Create a custom pipeline

Creating a pipeline is fairly easy. A pipeline is composed of a list of backends, the first one will be the default one, loaded at the start of the MultiBackend, the order of the rest isn’t important.

Each backend entry must specify one property: backend, containing the class of the Backend to instantiate. But other options are available:

Here is the rdndmb-html5-to-touch pipeline’s code as an example:

import { HTML5Backend } from 'react-dnd-html5-backend'
import { TouchBackend } from 'react-dnd-touch-backend'

import { DndProvider, TouchTransition, MouseTransition } from 'react-dnd-multi-backend'

export const HTML5toTouch = {
  backends: [
    {
      id: 'html5',
      backend: HTML5Backend,
      transition: MouseTransition,
    },
    {
      id: 'touch',
      backend: TouchBackend,
      options: {enableMouseEvents: true},
      preview: true,
      transition: TouchTransition,
    },
  ],
}

const App = () => {
  return (
    <DndProvider options={HTML5toTouch}>
      <Example />
    </DndProvider>
  )
}

Transitions

Transitions are required to allow switching between backends. They really easy to write, here is an example:

import { createTransition } from 'react-dnd-multi-backend'

const TouchTransition = createTransition('touchstart', (event) => {
  return event.touches != null
})

The following transitions are provided:

Note on skipDispatchOnTransition

By default, when an event triggers a transition, dnd-multi-backend dispatches a cloned version of the event after setting up the new backend. This allows the newly activated backend to handle the original event.

If your app code or another library has registered event listeners for the same events that are being used for transitions, this duplicate event may cause problems.

You can optionally disable this behavior per backend:

const CustomHTML5toTouch = {
  backends: [
    {
      backend: HTML5Backend,
      transition: MouseTransition
      // by default, will dispatch a duplicate `mousedown` event when this backend is activated
    },
    {
      backend: TouchBackend,
      // Note that you can call your backends with options
      options: {enableMouseEvents: true},
      preview: true,
      transition: TouchTransition,
      // will not dispatch a duplicate `touchstart` event when this backend is activated
      skipDispatchOnTransition: true
    }
  ]
}

WARNING: if you enable skipDispatchOnTransition, the backend transition will happen as expected, but the new backend may not handle the first event!

In this example, the first touchstart event would trigger the TouchBackend to replace the HTML5Backend—but the user would have to start a new touch event for the TouchBackend to register a drag.

Hooks

The library provides a set of hooks to expand useDrag and useDrop.

useMultiDrag

It expands useDrag and takes the same arguments but returns an array of:

Example:

import { useMultiDrag } from 'react-dnd-multi-backend'

const MultiCard = (props) => {
  const [[dragProps], {html5: [html5Props, html5Drag], touch: [touchProps, touchDrag]}] = useMultiDrag({
    type: 'card',
    item: {color: props.color},
    collect: (monitor) => {
      return {
        isDragging: monitor.isDragging(),
      }
    },
  })

  const containerStyle = {opacity: dragProps.isDragging ? 0.5 : 1}
  const html5DragStyle = {backgroundColor: props.color, opacity: html5Props.isDragging ? 0.5 : 1}
  const touchDragStyle = {backgroundColor: props.color, opacity: touchProps.isDragging ? 0.5 : 1}
  return (
    <div style={containerStyle}>
      <div style={html5DragStyle} ref={html5Drag}>HTML5</div>
      <div style={touchDragStyle} ref={touchDrag}>Touch</div>
    </div>
  )
}

useMultiDrop

It expands useDrop and takes the same arguments but returns an array of:

Example:

import { useMultiDrop } from 'react-dnd-multi-backend'

const MultiBasket = (props) => {
  const [[dropProps], {html5: [html5DropStyle, html5Drop], touch: [touchDropStyle, touchDrop]}] = useMultiDrop({
    accept: 'card',
    drop: (item) => {
      const message = `Dropped: ${item.color}`
      logs.current.innerHTML += `${message}<br />`
    },
    collect: (monitor) => {
      return {
        isOver: monitor.isOver(),
        canDrop: monitor.canDrop(),
      }
    },
  })

  const containerStyle = {border: '1px dashed black'}
  const html5DropStyle = {backgroundColor: (html5Props.isOver && html5Props.canDrop) ? '#f3f3f3' : '#bbbbbb'}
  const touchDropStyle = {backgroundColor: (touchProps.isOver && touchProps.canDrop) ? '#f3f3f3' : '#bbbbbb'}
  return (
    <div style={containerStyle}>
      <div style={html5DropStyle} ref={html5Drop}>HTML5</div>
      <div style={touchDropStyle} ref={touchDrop}>Touch</div>
    </div>
  )
}

Preview

The Preview class is usable in different ways: hook-based, function-based and context-based. All of them receive the same data formatted the same way, an object containing the following properties:

Note that this component will only be showed while using a backend flagged with preview: true (see Create a custom pipeline) which is the case for the Touch backend in the rdndmb-html5-to-touch pipeline.

Hook-based

import { DndProvider, usePreview } from 'react-dnd-multi-backend'

const MyPreview = () => {
  const preview = usePreview()
  if (!preview.display) {
    return null
  }
  const {itemType, item, style} = preview;
  // render your preview
}

const App = () => {
  return (
    <DndProvider options={MyPipeline}>
      <MyPreview />
    </DndProvider>
  )
}

Function-based

import { DndProvider, Preview } from 'react-dnd-multi-backend'

const generatePreview = ({itemType, item, style}) => {
  // render your preview
}

const App = () => {
  return (
    <DndProvider options={MyPipeline}>
      <Preview generator={generatePreview} />
      {/* or */}
      <Preview>{generatePreview}</Preview>
    </DndProvider>
  )
}

Context-based

import { DndProvider, Preview } from 'react-dnd-multi-backend'

const MyPreview = () => {
  const {itemType, item, style} = useContext(Preview.Context)
  // render your preview
}

const App = () => {
  return (
    <DndProvider options={MyPipeline}>
      <Preview>
        <MyPreview />
        // or
        <Preview.Context.Consumer>
          {({itemType, item, style}) => /* render your preview */}
        </Preview.Context.Consumer>
      </Preview>
    </DndProvider>
  )
}

Examples

You can see an example here.

Migrating

Migrating from 6.x.x

Starting with 7.0.0, HTML5toTouch will not be provided through this package anymore but through its own: rdndmb-html5-to-touch. It also doesn’t have a default export anymore.

Previously:

import MultiBackend from 'react-dnd-multi-backend'
import HTML5toTouch from 'react-dnd-multi-backend/dist/esm/HTML5toTouch'
// or
import HTML5toTouch from 'react-dnd-multi-backend/dist/cjs/HTML5toTouch'

Now:

import { MultiBackend } from 'react-dnd-multi-backend'
import { HTML5toTouch } from 'rdndmb-html5-to-touch'

Migrating from 5.0.x

Starting with 5.1.0, react-dnd-multi-backend will export a new DndProvider which you can use instead of the one from react-dnd. You don’t need to pass the backend prop to that component as it’s implied you are using MultiBackend, however the major benefits is under the hood:

Moreover, every backend in a pipeline will now need a new property called id and the library will warn if it isn’t specified. The MultiBackend will try to guess it if possible, but that might fail and you will need to define them explicitly.

Note that these aren’t breaking changes, you can continue using the library as before.

Migrating from 4.x.x

Starting with 5.0.0, react-dnd-preview (which provides the Preview component) will start passing its arguments packed in one argument, an object {itemType, item, style}, instead of 3 different arguments (itemType, item and style). This means that will need to change your generator function to receive arguments correctly.

Migrating from 3.x.x

Starting with 4.0.0, react-dnd-multi-backend will start using react-dnd (and the corresponding backends) 9.0.0 and later.

This means you need to transition from DragDropContext(MultiBackend(HTML5toTouch))(App) to <DndProvider backend={MultiBackend} options={HTML5toTouch}>. Accordingly, the pipeline syntax changes and you should specify backend options as a separate property, e.g. {backend: TouchBackend({enableMouseEvents: true})} becomes {backend: TouchBackend, options: {enableMouseEvents: true}}. Note that if you use the HTML5toTouch pipeline, the same is true for react-dnd-html5-backend and react-dnd-touch-backend.

Migrating from 3.1.2

Starting with 3.1.8, the dependencies of react-dnd-multi-backend changed. react, react-dom, react-dnd become peer dependencies and you need to install them manually as dependencies in your project package.json.

Note that if you use the HTML5toTouch pipeline, the same is true for react-dnd-html5-backend and react-dnd-touch-backend.

Migrating from 2.x.x

In 2.x.x, the pipeline was static but corresponded with the behavior of HTML5toTouch, so just including and passing this pipeline as a parameter would give you the same experience as before.

If you used the start option, it’s a bit different. With start: 0 or start: Backend.HTML5, MultiBackend simply used the default pipeline, so you can also just pass HTML5toTouch. With start: 1 or start: Backend.TOUCH, MultiBackend would only use the TouchBackend, so you can replace MultiBackend with TouchBackend (however, you would lose the Preview component) or create a simple pipeline (see Create a custom pipeline) and pass it as a parameter:

var TouchOnly = { backends: [{ backend: TouchBackend, preview: true }] }

License

MIT, Copyright (c) 2016-2022 Louis Brunner