react-swiperの矢印ナビゲーションをカスタマイズする方法

ReactまたはNext.jsのreact-swiperパッケージでSwiperスライドショーの矢印をカスタマイズする方法をまとめておきます。

サンプルコード

import React, { useRef } from "react";
import { Swiper, SwiperSlide } from "swiper/react";
import "swiper/css";

export const Slideshow = () => {
  const prevRef = useRef<HTMLDivElement>(null)
  const nextRef = useRef<HTMLDivElement>(null)
  return (
    <Swiper
      onInit={(swiper) => {
        swiper.params.navigation.prevEl = prevRef.current;
        swiper.params.navigation.nextEl = nextRef.current;
        swiper.navigation.init();
        swiper.navigation.update();
      }}
    >
      <SwiperSlide>Slide 1</SwiperSlide>
      <SwiperSlide>Slide 2</SwiperSlide>
      <div ref={prevRef}>Prev</div>
      <div ref={nextRef}>Next</div>
    </Swiper>
  );
}

useRefを活用してPrev, Nextボタン要素を作成します。Prev, Next箇所に任意のHTML要素を設置していけばオリジナルのナビゲーションを作成することができます。

まとめ

自力ではなかなかこのコードには行き着かなそうで、こうしたサンプルコードが見つかると嬉しいですね。

参考:[swiper/react] Custom navigation/pagination components using React refs not working/possible? #3855

ー この記事をシェアする? ー

この記事にコメントする

このサイトはreCAPTCHAとGoogleによって保護されています。プライバシーポリシー利用規約が適用されます。