Solid

Embla Carousel provides a wrapper for Solid that ensures seamless integration of the carousel into your Solid project and automatic cleanup on component unmount.

Start by installing the Embla Carousel npm package and add it to your dependencies.

npm install embla-carousel-solid --save

The component structure

Embla Carousel provides the handy createEmblaCarousel method for seamless integration with Solid. A minimal setup requires an overflow wrapper and a scroll container. Start by adding the following structure to your carousel:

import createEmblaCarousel from 'embla-carousel-solid'
export function EmblaCarousel() {  const [emblaRef] = createEmblaCarousel()
  return (    <div class="embla" ref={emblaRef}>      <div class="embla__container">        <div class="embla__slide">Slide 1</div>        <div class="embla__slide">Slide 2</div>        <div class="embla__slide">Slide 3</div>      </div>    </div>  )}

The method gives us a ref to attach to our wrapping element with the classname embla, which is needed to cover the scroll overflow. The element with the container classname is the scroll body that scrolls the slides. Continue by adding the following CSS to these elements:

.embla {  overflow: hidden;}.embla__container {  display: flex;}.embla__slide {  flex: 0 0 100%;  min-width: 0;}

The createEmblaCarousel method takes the Embla Carousel options as the first argument, which is a Solid accessor. Additionally, you can access the API with a onMount like demonstrated below:

import { onMount } from 'solid-js'import createEmblaCarousel from 'embla-carousel-solid'
export function EmblaCarousel() {  const [emblaRef, emblaApi] = createEmblaCarousel(() => ({ loop: true }))
  onMount(() => {    const api = emblaApi()    if (api) {      console.log(api.slideNodes()) // Access API    }  })
  return (    <div class="embla" ref={emblaRef}>      <div class="embla__container">        <div class="embla__slide">Slide 1</div>        <div class="embla__slide">Slide 2</div>        <div class="embla__slide">Slide 3</div>      </div>    </div>  )}

Adding plugins

Start by installing the plugin you want to use. In this example, we're going to install the Autoplay plugin:

npm install embla-carousel-autoplay --save

The createEmblaCarousel method accepts plugins as the second argument, which is a Solid accessor. Note that plugins need to be passed in an array like so:

import createEmblaCarousel from 'embla-carousel-solid'import Autoplay from 'embla-carousel-autoplay'
export function EmblaCarousel() {  const [emblaRef] = createEmblaCarousel(    () => ({ loop: true }),    () => [AutoPlay()]  )
  return (    <div class="embla" ref={emblaRef}>      <div class="embla__container">        <div class="embla__slide">Slide 1</div>        <div class="embla__slide">Slide 2</div>        <div class="embla__slide">Slide 3</div>      </div>    </div>  )}

Congratulations! You just created your first Embla Carousel component.

Edit this page on GitHub