LoginSignup
4
2

More than 1 year has passed since last update.

React で Swiper 使用する方法

Last updated at Posted at 2022-09-24

はじめに

Gatsby.jsにてスライドを実装ときにハマったので、メモです。
Gatsby.jsに限らずReactでも同じかと思います。

やりたいこと

Gatsby.jsにスライドショーを実装したい。
機能的には以下を実装。

  • autoプレイ(roop)
  • ページネーション

参考サイト

Swiper バージョン

参考記事に

Reactで扱う場合は、 swiper@6.8.4を利用する。7/8は利用できない。

とありましたが、私の場合現時点での最新でも動きました!

"swiper": "^8.4.2"

実装方法


import React from 'react'
import SwiperCore, { Autoplay, Pagination } from 'swiper'
import { Swiper, SwiperSlide } from 'swiper/react'
import 'swiper/swiper.min.css'
import 'swiper/swiper-bundle.min.css'

SwiperCore.use([Pagination, Autoplay])  // ← ページネーション、autoプレイ、ナビゲーションはここでuseで拡張する

// 今回のスライドは以下のようなパラメータで実装しました。

const params = {
  slidesPerView: 1,
  spaceBetween: 30,
  centeredSlides: true,
  loop: true,    // autoで無限ループにしたい場合にはここをtrue
  loopedSlides: 5, // ここに数値いれないと、無限ループにはなるが、最後から最初へ切り替わる時キレてしまう。。
  autoplay: {
    delay: 3000,
    disableOnInteraction: false,
  },
  pagination: {
    clickable: true,
  },
}

・・・ // ソース 詳細は略します。。

return (
        <ul className="swiper-wrapper">
          <Swiper {...params}>
            {persons.map(person => {
              return (
                <SwiperSlide>
                  <li key={person.slug}>
                 // スライド中身
                  </li>
                </SwiperSlide>
              )
            })}
          </Swiper>
        </ul>
      )



以上です!

4
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
2