How to use Autoplay with Embla carousel in next/js?

2.1k Views Asked by At

I have a working Embla carousel in next/js, very similar to this example. To make it work, I had to add use client at the top of the file. I'm trying to add Autoplay capability using this library. The working relevant code is the following:

'use client'

import useEmblaCarousel from 'embla-carousel-react'

export const EmblaCarousel = (props) => {
    const options = { loop: true };

    const [emblaRef, emblaApi] = useEmblaCarousel(
        options
    );
}

If I add the Autoplay, by changing it to:

'use client'

import useEmblaCarousel from 'embla-carousel-react'


export const EmblaCarousel = (props) => {
    const options = { loop: true };

    const [emblaRef, emblaApi] = useEmblaCarousel(
        options, [Autoplay()]
    );
}

I get the following error:

Unhandled Runtime Error

TypeError: node is undefined

Call Stack
add
node_modules/embla-carousel-react/node_modules/embla-carousel/embla-carousel.esm.js (195:0)
init
node_modules/embla-carousel-autoplay/embla-carousel-autoplay.esm.js (43:0)
init/<
node_modules/embla-carousel-react/node_modules/embla-carousel/embla-carousel.esm.js (1269:0)
init
node_modules/embla-carousel-react/node_modules/embla-carousel/embla-carousel.esm.js (1269:0)
activate
node_modules/embla-carousel-react/node_modules/embla-carousel/embla-carousel.esm.js (1326:0)
EmblaCarousel
node_modules/embla-carousel-react/node_modules/embla-carousel/embla-carousel.esm.js (1457:0)
useEmblaCarousel/<
node_modules/embla-carousel-react/embla-carousel-react.esm.js (16:36)

I tried also to use Autoplay with some options, but always got the same result. Could you help?

3

There are 3 best solutions below

1
CharlesAE On

EmblaCarousel expects an object of type EmblaOptionsType

You need to specify the correct type for options

  1. Adjust your imports

    import useEmblaCarousel, { EmblaOptionsType } from "embla-carousel-react";

  2. Set options to type 'EmblaOptionsType'

    const options: EmblaOptionsType = { loop: true };

0
Heartbit On

You should import autoplay plugin first and apply it to embla hook.

import Autoplay from "embla-carousel-autoplay";


const [emblaRef, emblaApi] = useEmblaCarousel(
        options, [Autoplay()]
    );
0
Hadnazzar On

There is an external plugin for embla carousel react to use autoplay.

embla-carousel-autoplay

You can see the documentation here: https://github.com/davidjerleke/embla-carousel/tree/master/packages/embla-carousel-autoplay

Then in useEmblaCarousel hook you should call it like this

import Autoplay from "embla-carousel-autoplay";


const [emblaRef, emblaApi] = useEmblaCarousel(OPTIONS, [Autoplay()]);