Repository navigation
[Help]: Dynamic Axis Locking for Nested Carousels to Prevent Simultaneous Dragging #1154
SummaryIs there a way to dynamically update or lock the drag on a specific axis in embla-carousel-react—using, for example, a dynamic watchDrag callback or another API—so that I can prevent simultaneous dragging in both directions when I have nested carousels (one vertical and one horizontal) without needing to reinitialize the carousel each time the lock state changes? If applicable, which variants of Embla Carousel are relevant to this question?
Additional informationconst [lockX, setLockX] = useState(false)
const [lockY, setLockY] = useState(false)
const [emblaRef, emblaApi] = useEmblaCarousel({
duration: 20,
axis: 'y',
loop: true,
align: 'center',
watchDrag: (emblaApi) => isScrollable(emblaApi, lockY)
});
useEffect(() => {
if (!emblaApi) return;
emblaApi.reInit({
axis: 'y',
loop: true,
align: 'center',
watchDrag: (emblaApi) => isScrollable(emblaApi, lockY)
});
}, [emblaApi, lockY]);
const [emblaRef, emblaApi] = useEmblaCarousel({
duration: 20,
loop: false,
align: 'center',
watchDrag: (emblaApi) => isScrollable(emblaApi, lockX)
});
useEffect(() => {
if (!emblaApi) return;
emblaApi.reInit({
loop: false,
align: 'center',
watchDrag: (emblaApi) => isScrollable(emblaApi, lockX)
});
}, [emblaApi, lockX]);CodeSandbox exampleNo response |
Replies: 1 comment 1 reply
|
Hi @maoi-dev,
Thank you for your question. If I understand your question correctly, then yes, it's possible. Embla options are reactive so you don't want to change the state of options because that will trigger a reset of a carousel (and stop any ongoing animation). Simply use a const isMainCarouselDragDisabled = useRef(false)
const [emblaMainRef, emblaMainApi] = useEmblaCarousel({
watchDrag: (emblaApi) => !isMainCarouselDragDisabled.current
});
const [emblaNestedRef, emblaNestedApi] = useEmblaCarousel({});
useEffect(() => {
if (!emblaNestedApi) return
function handleParentCarouselDragLock(_, eventName) {
const lockParentDrag = eventName === 'pointerDown'
isMainCarouselDragDisabled.current = lockParentDrag
}
emblaNestedApi.on('pointerDown', handleParentCarouselDragLock)
emblaNestedApi.on('pointerUp', handleParentCarouselDragLock)
}, [emblaNestedApi]) |
Hi @maoi-dev,
Thank you for your question. If I understand your question correctly, then yes, it's possible. Embla options are reactive so you don't want to change the state of options because that will trigger a reset of a carousel (and stop any ongoing animation). Simply use a
react refto prevent this: