Swiper React Componentsが将来廃止になるということでSwiper Element (WebComponent)をnext.jsのプロジェクトに導入する際、なぜか横並びにならなくて詰まったので備忘。
"next": "14.2.3",
"react": "^18",
"swiper": "^11.1.3"
うまくいかなかった時の画面
slides-per-view="1"の設定でもswiper-slideの数だけ横並びになってしまった。
うまくいったときの画面
原因
原因はreset.scssに書かれていた以下記述部分
swiper-slideに「all: unset;」が効いてしまっていたことが原因だった。
all - CSS: カスケーディングスタイルシート | MDN
reset.scss
*:where(
:not(html, iframe, canvas, img, svg, video, audio):not(
svg *,
symbol *
)
) {
all: unset;
display: revert;
}
:notのところに「swiper-slide」を追加することでうまく動作した。
reset.scss
*:where(
:not(html, iframe, canvas, img, svg, video, audio, swiper-slide):not(
svg *,
symbol *
)
) {
all: unset;
display: revert;
}
Swiper Elementを使用した書き方
SwiperComponents.js
"use client";
import React from "react";
import { register } from "swiper/element/bundle";
register();
export default function SwiperComponent() {
return (
<swiper-container
slides-per-view="1"
navigation="true"
pagination="true"
space-between={30}
>
<swiper-slide key="1">Slide 1</swiper-slide>
<swiper-slide key="2">Slide 2</swiper-slide>
<swiper-slide key="3">Slide 3</swiper-slide>
</swiper-container>
);
}
ページネーションのドットのスタイル変更CSS
swiper-container {
&::part(container) {
padding-bottom: 25px;
}
&::part(pagination) {
bottom: 0;
}
&::part(bullet) {
width: 30px;
height: 3px;
opacity: 0.8;
background: #fff;
border-radius: 0;
}
&::part(bullet-active) {
width: 30px;
height: 3px;
border-radius: 0;
background-color: $color-accent;
}
}
完成形
左右の矢印は不要だったので「navigation="true"」は外しました。
ちなみにSwiper React Componentsを使用した書き方
SwiperComponents.js
"use client";
import React from "react";
import { Navigation, Pagination } from "swiper/modules";
import { Swiper, SwiperSlide } from "swiper/react";
import "swiper/css";
import "swiper/css/navigation";
import "swiper/css/pagination";
export default function SwiperComponent() {
return (
<>
<Swiper
modules={[Navigation, Pagination]}
spaceBetween={50}
slidesPerView={1}
navigation
pagination={{ clickable: true }}
onSlideChange={() => console.log("slide change")}
onSwiper={(swiper) => console.log(swiper)}
>
<SwiperSlide>Slide 1</SwiperSlide>
<SwiperSlide>Slide 2</SwiperSlide>
<SwiperSlide>Slide 3</SwiperSlide>
<SwiperSlide>Slide 4</SwiperSlide>
</Swiper>
</>
);
}
参考サイト