embla-carousel-react
Integrates Embla Carousel into React through a lifecycle-aware hook.
- Downloads / mo
- 109.7M
- Stars
- 8.5K
- Last release
- 8.6.0
- License
- MIT
Strengths
- Cleans up on unmount. The React wrapper removes carousel resources when its component unmounts.
- Exposes a carousel control API. Access the carousel API returned by useEmblaCarousel.
Limitations
- Looping can fall back. Looping is disabled when too little slide content can support it.
- Autoplay needs an extra package. Install embla-carousel-autoplay when slides should advance automatically.
Quickstart
import React, { useEffect } from 'react' import useEmblaCarousel from 'embla-carousel-react' export function EmblaCarousel() { const [emblaRef, emblaApi] = useEmblaCarousel({ loop: false }) useEffect(() => { if (emblaApi) { console.log(emblaApi.slideNodes()) // Access API } }, [emblaApi]) return ( <div className="embla" ref={emblaRef}> <div className="embla__container"> <div className="embla__slide">Slide 1</div> <div className="embla__slide">Slide 2</div> <div className="embla__slide">Slide 3</div> </div> </div> ) }
embla-carousel-react examples
function Carousel({ orientation = "horizontal", opts, setApi, plugins, className, children, ...props }: React.ComponentProps<"div"> & CarouselProps) { const [carouselRef, api] = useEmblaCarousel( { ...opts, axis: orientation === "horizontal" ? "x" : "y", }, plugins ) const [canScrollPrev, setCanScrollPrev] = React.useState(false) const [canScrollNext, setCanScrollNext] = React.useState(false) const onSelect = React.useCallback((api: CarouselApi) => { if (!api) return setCanScrollPrev(api.canScrollPrev()) setCanScrollNext(api.canScrollNext()) }, []) const scrollPrev = React.useCallback(() => { api?.scrollPrev() }, [api]) const scrollNext = React.useCallback(() => { api?.scrollNext() }, [api]) const handleKeyDown = React.useCallback( (event: React.KeyboardEvent<HTMLDivElement>) => { if (event.key === "ArrowLeft") { event.preventDefault() scrollPrev() } else if (event.key === "ArrowRight") { event.preventDefault() scrollNext() } }, [scrollPrev, scrollNext] ) React.useEffect(() => { if (!api || !setApi) return setApi(api) }, [api, setApi]) React.useEffect(() => { if (!api) return onSelect(api) api.on("reInit", onSelect) api.on("select", onSelect) return () => { api?.off("select", onSelect) } }, [api, onSelect]) return ( <CarouselContext.Provider value={{ carouselRef, api: api, opts, orientation: orientation || (opts?.axis === "y" ? "vertical" : "horizontal"), scrollPrev, scrollNext, canScrollPrev, canScrollNext, }} > <div onKeyDownCapture={handleKeyDown} className={cn("relative", className)} role="region" aria-roledescription="carousel" data-slot="carousel" {...props} > {children} </div> </CarouselContext.Provider> ) }