javascript - How to turn onoff the embla carousel by breakpoint in React? - Stack Overflow

Using the Embla Carousel, React version, I'm trying to turnon off the carousel based on breakpoin

Using the Embla Carousel, React version, I'm trying to turn/on off the carousel based on breakpoint. So for mobile, it's on and for tablet up it's off. Here's what I tried that seems to work initially, but won't reinitialize. I'm guessing it's because destory was called so it can reInit and tried init, but no luck there either.

const emblaOptions = {};
  const [viewportRef, emblaApi] = useEmblaCarousel(emblaOptions);

  const handleEmblaInit = () => {
    if (window.innerWidth > 768) {
      emblaApi.destroy();
    } else {
      emblaApi.reInit(emblaOptions);
    }
  };

  useEffect(() => {
    if (emblaApi) {
      handleEmblaInit();
      window.addEventListener("resize", handleEmblaInit);
    }
  }, [emblaApi]);

Using the Embla Carousel, React version, I'm trying to turn/on off the carousel based on breakpoint. So for mobile, it's on and for tablet up it's off. Here's what I tried that seems to work initially, but won't reinitialize. I'm guessing it's because destory was called so it can reInit and tried init, but no luck there either.

const emblaOptions = {};
  const [viewportRef, emblaApi] = useEmblaCarousel(emblaOptions);

  const handleEmblaInit = () => {
    if (window.innerWidth > 768) {
      emblaApi.destroy();
    } else {
      emblaApi.reInit(emblaOptions);
    }
  };

  useEffect(() => {
    if (emblaApi) {
      handleEmblaInit();
      window.addEventListener("resize", handleEmblaInit);
    }
  }, [emblaApi]);
Share Improve this question asked Apr 21, 2022 at 13:54 Ben MarshallBen Marshall 1,7642 gold badges18 silver badges35 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 5

From version 7 and up you can use the active option together with the breakpoints option to achieve this. Example from the Embla Carousel docs:

const options = {
  active: true,
  breakpoints: {
    '(min-width: 768px)': { active: false },
  },
}

Usage with React:

const [emblaRef, emblaApi] = useEmblaCarousel({
  active: true,
  breakpoints: {
    '(min-width: 768px)': { active: false },
  },
});

Pass null instead of the emblaRef when you want it to be inactive, like demonstrated here:

https://github./davidcetinkaya/embla-carousel/issues/99#issuement-688730519

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745299713a4621362.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信