Created
March 10, 2023 00:59
-
-
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 file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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