티스토리 뷰
반응형
[nextjs/swiper] nextjs 환경에서 완벽한 반응형 swiper 구현
#swiperjs를 활용하여 완벽한 반응형 swiper 구현
사용해본 결과 swiperjs는 버전에 따라서, function들이 제법 바뀌어서 그냥 고정 버전으로 설명 후 해당 버전을 이용하는 걸 추천한다.
#설치 (11.0.7)
npx create-react-app
npm install swiper
#Page.tsx
import logo from './logo.svg';
import './App.css';
import { Swiper, SwiperSlide } from "swiper/react";
import { Autoplay, Navigation } from "swiper/modules";
import SwiperCore from "swiper";
import "swiper/css";
import "swiper/css/navigation";
import { useRef } from 'react';
function App() {
const sliderRef = useRef(null);
const handlePrev = useCallback(() => {
if (!sliderRef.current) return;
sliderRef.current.swiper.slidePrev();
}, []);
const handleNext = useCallback(() => {
if (!sliderRef.current) return;
sliderRef.current.swiper.slideNext();
}, []);
SwiperCore.use([Autoplay, Navigation]);
const sliderImages = [
"/test/2-1.png",
"/test/2-2.png",
"/test/2-3.png",
"/test/2-4.png",
];
const prevRef = useRef(null);
const nextRef = useRef(null);
return (
<div className="App">
<Swiper
ref={sliderRef}
loop={true}
slidesPerView={1}
spaceBetween={1}
className="w-full bg-white"
autoplay={{
delay: 3000,
disableOnInteraction: false,
}}
onSwiper={(swiper)=>{
// swiperRef.current = swiper;
}}
onInit={(swiper) => {
swiper.navigation.init();
swiper.navigation.update();
}}
modules={[Navigation, Autoplay]}
>
{sliderImages.map((value, index) => {
return (
<SwiperSlide>
<div>{index}</div>
<img
src={`${value}`}
className="object-contain w-full h-full"
alt=""
/>
</SwiperSlide>
);
})}
<div className="flex justify-between mt-4">
<Image
src="/images/left.png"
width={40}
height={40}
className="-mt-4"
onClick={handlePrev}
alt=""
/>
<div style={{ fontSize: "9px", fontWeight: "700" }}>
MOTUNGIWOO SINSA
</div>
<Image
src="/images/right.png"
width={40}
height={40}
className="-mt-4"
onClick={handleNext}
alt=""
/>
</div>
</Swiper>
</div>
);
}
export default App;
반응형
댓글
반응형