はじめに
Embla-Carouselとは、非依存型でシンプルなカルーセルライブラリです。
様々なオプションがあり、自由度高く設定することができます。
Embla-Carouselにはサンプルが多く転記し易いですが、バージョンによるオプション等の指定方法も異なります。
今回はEmbla Carouselで自動的にカルーセルを流す方法、
何秒おきに流すかを指定する方法を記します。
環境
- Next.js:14.0.3
embla-carousel-react:^8.0.0-rc22
embla-carousel-autoplay:^8.0.0-rc22
embla-carousel:^8.0.0-rc22
Embla Carouselで自動的にカルーセルを流す方法
パッケージのインストール
まずは必要なパッケージをインストールします。
npm install embla-carousel-react embla-carousel embla-carousel-autoplay
オプションの指定
公式サンプルと同じ構成なので、省略して記します。
home/page.tsx
'use client'
import EmblaCarousel from '@/ui/atom/carousel/emblaCarousel';
import { EmblaOptionsType } from 'embla-carousel'
const Home = () => {
const OPTIONS: EmblaOptionsType = {
loop: true,
slidesToScroll: 1,
duration: 50
}
return (
<EmblaCarousel slides={Items} options={OPTIONS} />
)
}
export default Home;
-
loop
スライドが終端までいったときに始端に戻るようにする設定。trueで有効。 -
slidesToScroll
自動再生時に使われるオプション。1ならスライドが1枚ずつ自動再生される。 -
duration
スクロールのアニメーション時間。数値が大きいほど遅くなる(単位はミリ秒ではない)。
Embla Carouselで自動カルーセルの時間を設定する方法
この設定はEmblaCarouselコンポーネント内に記述します。
以下はその一部の例です。
emblaCarousel.tsx
import { EmblaOptionsType } from 'embla-carousel'
import Autoplay from 'embla-carousel-autoplay'
import useEmblaCarousel from 'embla-carousel-react'
const TWEEN_FACTOR = 4.2
const numberWithinRange = (number: number, min: number, max: number): number =>
Math.min(Math.max(number, min), max)
type PropType = {
slides: T[]
options?: EmblaOptionsType
}
const EmblaCarousel = (props: React.PropsWithChildren<PropType>) => {
const { slides, options } = props
const [emblaRef, emblaApi] = useEmblaCarousel(options, [Autoplay({ delay: 2000 })])
// 以下略
}
以下のように設定します:
-
Autoplay({ delay: 2000 })
→ 2000ミリ秒(2秒)ごとにスライドを切り替えます。 -
import Autoplay from 'embla-carousel-autoplay'
→ 自動再生用プラグインを読み込みます。
Autoplayの設定項目
上記設定で自動再生は動作しますが、さらに詳しい設定も可能です。
embla-carousel-autoplay
の型定義ファイルを確認すると、以下のようなオプションがあります。
Auto.d.ts
export type AutoplayType = CreatePluginType<{
play: (jump?: boolean) => void;
stop: () => void;
reset: () => void;
isPlaying: () => boolean;
}, OptionsType>;
export type AutoplayOptionsType = AutoplayType['options'];
declare function Autoplay(userOptions?: AutoplayOptionsType): AutoplayType;
declare namespace Autoplay {
var globalOptions: Partial<import("embla-carousel/components/Options").CreateOptionsType<OptionsType> | undefined>;
}
export default Autoplay;
Options.d.ts
import { CreateOptionsType } from 'embla-carousel/components/Options';
export type OptionsType = CreateOptionsType<{
delay: number;
jump: boolean;
playOnInit: boolean;
stopOnFocusIn: boolean;
stopOnInteraction: boolean;
stopOnMouseEnter: boolean;
stopOnLastSnap: boolean;
rootNode: ((emblaRoot: HTMLElement) => HTMLElement | null) | null;
}>;
export declare const defaultOptions: OptionsType;
このように、delay以外にも下記のような制御が可能です:
jump
: スライドをジャンプ的に切り替えるplayOnInit
: 初期化時に自動再生を開始stopOnFocusIn
: フォーカス時に停止stopOnMouseEnter
: ホバーで停止 など
参考文献
おわりに
非常にシンプルなライブラリで、最小限の導入で使えました。
依存性はなく、競合も起こりにくいですが、スタイルの指定は必要です。
サンプルも豊富なので、導入もスムーズに進められました。