내가 만들려고 했던 컴포넌트에 슬라이드 기능이 있어 회사에서 일하면서 밥 먹듯 썼던 스와이프 슬라이드를 써보려했다. 그런데 react로 쓰는 건 또 새로워서 기록으로 남겨보고자 한다. 아래는 내가 구현할 슬라이드!
기존에 알고 있던 자바스크립트로 구현하는 스와이프 슬라이드는 이러하다.
https://swiperjs.com/swiper-api
Swiper API
Swiper is the most modern free mobile touch slider with hardware accelerated transitions and amazing native behavior.
swiperjs.com
<!-- Slider main container -->
<div class="swiper">
<!-- Additional required wrapper -->
<div class="swiper-wrapper">
<!-- Slides -->
<div class="swiper-slide">Slide 1</div>
<div class="swiper-slide">Slide 2</div>
<div class="swiper-slide">Slide 3</div>
...
</div>
<!-- If we need pagination -->
<div class="swiper-pagination"></div>
<!-- If we need navigation buttons -->
<div class="swiper-button-prev"></div>
<div class="swiper-button-next"></div>
<!-- If we need scrollbar -->
<div class="swiper-scrollbar"></div>
</div>
슬라이드를 감싸주는 wrapper가 필요하고, 페이지네이션이나 네비게이션, 스크롤바가 필요하다면 추가 후 그걸 감싸주는 container가 또 있다. HTML에서 이러한 코드를 작성하고, Javascript에서 기능을 하게끔 또 코드 작성이 필요하다.
const swiper = new Swiper('.swiper', {
slidesPerView: 1,
spaceBetween: 10,
loop: true,
autoplay: {
delay: 5000,
},
navigation: {
nextEl: '.swiper-button-next',
prevEl: '.swiper-button-prev',
},
pagination: {
el: '.swiper-pagination',
type: 'bullets',
},
});
클래스명 혹은 아이디명으로 슬라이더를 불러와 옵션을 부여해준다. slick slider나 bx slider 등 다른 슬라이드도 많지만 그간 써왔던 swiper slide를 react로 써보는 것도 좋을 것 같아 이번에도 swiper slide를 택했다.
Swiper React Components
Swiper is the most modern free mobile touch slider with hardware accelerated transitions and amazing native behavior.
swiperjs.com
먼저 스와이퍼를 install 한다. 시작부터 기존과 달라...!
npm i swiper
import styled from 'styled-components';
import { Navigation, Pagination } from 'swiper';
import { Swiper, SwiperSlide } from 'swiper/react';
import 'swiper/css';
import 'swiper/css/navigation';
import 'swiper/css/pagination';
const CardSlide = ({ images }) => {
return (
<Carousel
modules={[Navigation, Pagination]}
slidesPerView={1}
navigation
pagination={{
clickable: true,
dynamicBullets: true,
dynamicMainBullets: 3,
}}
>
{images.map((data, idx) => {
return (
<SwiperSlide key={idx}>
<img src={data} alt="slide" />
</SwiperSlide>
);
})}
</Carousel>
);
};
필요한 기능을 import하고, 컴포넌트에 직접 모듈을 넣어주었다.
<SwiperSlide>Slide 1</SwiperSlide>
<SwiperSlide>Slide 2</SwiperSlide>
<SwiperSlide>Slide 3</SwiperSlide>
...
이렇게 일일이 작성한다면 리액트를 쓸 필요가 없겠지?! 반복되는 부분은 map으로 뿌려주었다.
그런데 swiper 사이트에는 <Swiper>로 컴포넌트화했는데 왜 <Carousel>로 컴포넌트명을 바꿨냐하면, 스타일 컴포넌트 때문이다. 스타일 컴포넌트에서 const Swiper = styled.div` `; 로 작성하려 하니 이미 선언되어있다고 하는 것! 넘나 당연하다.
const Carousel = styled(Swiper)`
img {
width: 100%;
height: 100%;
object-fit: cover;
}
`;
어떤 이미지가 들어와도 화면에 가득차야 하기 때문에 스타일값까지 지정 완료⭐
'TIL > Project' 카테고리의 다른 글
[>wecode] 2차 프로젝트 회고록(2) - 에어비앤비 클론코딩 (0) | 2022.08.17 |
---|---|
[>wecode] 2차 프로젝트 회고록 - 에어비앤비 클론코딩 (0) | 2022.08.13 |
[React] 스크롤 시 nav 스타일 변화 (0) | 2022.08.04 |
[React] CRA 초기세팅 (0) | 2022.08.03 |
[>wecode] 1차 프로젝트 회고록(2) - 오설록 클론코딩 (2) | 2022.07.31 |