TypeScript Support
Embla Carousel is written in TypeScript and provides first-class type definitions out of the box. Leveraging these types ensures type safety for your carousel instances, configuration options, and plugin setups.
Typing the API
The most commonly used type is EmblaCarouselType, which represents the API instance returned by the initializer. This is particularly useful when passing the API as a prop to components or storing it in a variable.
import EmblaCarousel, { EmblaCarouselType } from 'embla-carousel'
let emblaApi: EmblaCarouselType | undefined
const onInit = (api: EmblaCarouselType) => {
emblaApi = api
}
Configuration Options
You can type your options object using EmblaOptionsType. This provides autocomplete for all available settings like loop, align, and breakpoints.
import { EmblaOptionsType } from 'embla-carousel'
const options: EmblaOptionsType = {
loop: true,
align: 'start',
breakpoints: {
'(min-width: 768px)': { loop: false }
}
}
Plugin Support
When using plugins, you can use the generic EmblaPluginType for general plugin configurations, or import specific types provided by the plugin packages for better IDE intellisense.
Typing the Plugins Array
If you are defining a list of plugins outside of the initializer:
import { EmblaPluginType } from 'embla-carousel'
import Autoplay from 'embla-carousel-autoplay'
const plugins: EmblaPluginType[] = [
Autoplay({ delay: 4000 })
]
Accessing Plugin APIs
Plugins often expose their own internal methods. You can cast the plugin instance to its specific type to access these methods safely.
import EmblaCarousel from 'embla-carousel'
import Autoplay, { AutoplayType } from 'embla-carousel-autoplay'
const emblaApi = EmblaCarousel(viewportNode, {}, [Autoplay()])
// Accessing the autoplay API safely
const autoplay = emblaApi.plugins().autoplay as AutoplayType
autoplay.stop()
Framework Wrappers
If you are using one of the official framework wrappers (React, Vue, Svelte, etc.), the hooks and components are already typed. You can still import core types from embla-carousel to type your custom functions or effects.
React Example
import React, { useCallback } from 'react'
import { EmblaCarouselType } from 'embla-carousel'
import useEmblaCarousel from 'embla-carousel-react'
export const EmblaCarousel = () => {
const [emblaRef, emblaApi] = useEmblaCarousel()
const onSelect = useCallback((api: EmblaCarouselType) => {
console.log(`Current index is ${api.selectedSnap()}`)
}, [])
// ...
}
Event Typing
When listening to events via .on() or .off(), the callback receives the API instance as the first argument and the event name/detail as subsequent arguments.
const logScroll = (emblaApi: EmblaCarouselType, eventName: string): void => {
console.log(`Embla fired: ${eventName}`)
}
emblaApi.on('scroll', (api) => logScroll(api, 'scroll'))