Skip to content

Instantly share code, notes, and snippets.

@rileyjshaw
Created March 10, 2023 00:59
Show Gist options
  • Save rileyjshaw/2fed2f398ffdca88b7747f2ab03d8a9b to your computer and use it in GitHub Desktop.
Save rileyjshaw/2fed2f398ffdca88b7747f2ab03d8a9b to your computer and use it in GitHub Desktop.
A small wrapper around React DnD’s provider that switches to a touch backend as soon as a touch event is detected.
// This is a small wrapper around React DnD’s provider that switches to a touch
// backend as soon as a touch event is detected.
import { useEffect, useState } from 'react';
import { DndProvider } from 'react-dnd';
import { HTML5Backend } from 'react-dnd-html5-backend';
const TOUCH_EVENTS = ['touchstart', 'touchmove', 'touchend', 'touchcancel'];
function DndProviderWrapper({ children }) {
const [dndProps, setDndProps] = useState({ backend: HTML5Backend });
// If the user triggers a touch event, it means they are using their
// touchscreen. This is better than checking if the device supports touch
// events, because the user may still prefer to use a mouse.
useEffect(() => {
function touchHandler() {
removeHandlers();
import('react-dnd-touch-backend').then(({ TouchBackend }) => {
setDndProps({
backend: TouchBackend,
options: {
enableMouseEvents: true,
},
});
});
}
TOUCH_EVENTS.forEach(touchEvent => {
document.addEventListener(touchEvent, touchHandler, { once: true, passive: true });
});
function removeHandlers() {
TOUCH_EVENTS.forEach(touchEvent => {
document.removeEventListener(touchEvent, touchHandler);
});
}
return removeHandlers;
}, []);
return <DndProvider {...dndProps}>{children}</DndProvider>;
}
export default DndProviderWrapper;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment