LoginSignup
14
6

More than 1 year has passed since last update.

[Next.js+Typescript] Swiperでカルーセルを作成する

Last updated at Posted at 2022-01-02

Webで実装したことを記事にしました。
カルーセルを作ることになり、Swiperについて、いろいろと調べたので、
まとめるために記事にしました。

同じようなことを実装するときに、この記事が少しでもお役に立てれば幸いです。

Swiperをインストールする

まずはドキュメントを参考にしました。

  $ npm install swiper

cssをインポートします。私は、_app.tsxに追加しました。

import 'swiper/css/bundle'

カルーセルを作成する

import Image from 'next/image'
import { Swiper, SwiperSlide } from 'swiper/react' //カルーセル用のタグをインポート
import SwiperCore, { Pagination, Navigation } from 'swiper' //使いたい機能をインポート

SwiperCore.use([Pagination, Navigation]) 

// カルーセルにする画像のソースをリストにします
const images = [
  '/test_image.jpg',
  '/test_image2.jpg',
  '/test_image.jpg',
  '/test_image2.jpg',
]

const TestCarousel = () => {
  return (
    <Swiper
      slidesPerView={1} //一度に表示するスライドの数
      pagination={{
        clickable: true,
      }} // 何枚目のスライドかを示すアイコン、スライドの下の方にある
      navigation //スライドを前後させるためのボタン、スライドの左右にある
      loop={true}
    >
      {images.map((src: string, index: number) => {
        return (
          <SwiperSlide key={`${index}`}>
            <Image
              src={src}
              layout="responsive"
              width={640}
              height={400}
              alt="test_image"
            />
          </SwiperSlide>
        )
      })}
    </Swiper>
  )
}

export default TestCarousel

test_carousel.jpg

スライドの左右にnavigationがあり、スライドの下の方にはpaginationが表示されています。
デフォルトでは両方とも、色が青なので、CSSの変更がしたいところです。

さらに、機能を追加してCSSを変更するところは、別記事にまとめます。

最後に

参考にしたサイトは、下に貼ってあります.
間違っているところやよりよい方法をご存知の方がいれば、ご指摘いただけると助かります。

参考にしたサイト

14
6
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
14
6