React-slick으로 슬라이드 만들기

Jin·2022년 3월 1일
0

React

목록 보기
7/17

일단, npm 혹은 yarn으로 react-slick과 slick-carousel을 설치합니다.

npm install react-slick, npm install slick-carousel

혹은

yarn add react-slick, yarn add slick-carousel

(타입스크립트 사용시 @types/react-slick 추가 설치)

가장 먼저, 슬라이드 설정을 해줘야 합니다.

const settings = {
        dots: false,
        infinite: true,
        speed: 500,
        slidesToShow: 9,
        slidesToScroll: 9,
        initialSlide: 0,
        responsive: [
            {
                breakpoint: 1440,
                settings: {
                    slidesToShow: 7,
                    slidesToScroll: 7
                }
            },
            {
                breakpoint: 1024,
                settings: {
                    slidesToShow: 5,
                    slidesToScroll: 5
                }
            },
            {
                breakpoint: 720,
                settings: {
                    slidesToShow: 3,
                    slidesToScroll: 3
                }
            },
            {
                breakpoint: 480,
                settings: {
                    slidesToShow: 2,
                    slidesToScroll: 2
                }
            },
            {
                breakpoint: 320,
                settings: {
                    slidesToShow: 1,
                    slidesToScroll: 1
                }
            }
        ]
    };
  • dot: 슬라이드 밑에 점으로 나타내는 것을 보여주냐 여부 설정
  • slidesToShow: 몇 개의 슬라이드를 보여줄 것인지를 설정하고
  • slidesToScroll은 옆으로 넘길 때 몇 개의 슬라이드가 넘어가게 할 것인지를 설정
  • responsive: 화면 크기에 따른 슬라이드 크기 설정
import React from "react";
import styled from "styled-components";
import Slider from "react-slick";


const Container = styled.div`
    margin-top: 10px;
    :not(:last-child) {
        margin-bottom: 50px;
    }
`;

const Title = styled.span`
    font-size: 20px;
    font-weight: 600;
`;

const Grid = styled.div`
    margin-top: 30px;
    display: grid;
    grid-template-columns: repeat(auto-fill, 150px);
    grid-gap: 25px;
`;

const Wrapper = styled.div`
    margin: 40px auto; 
    width: 95%;
`;

interface Props {
    slide: boolean,
    title?: string,
    children: React.ReactNode
}

const Section: React.FunctionComponent<Props> = ({ slide, title, children }) => {
    const settings = {
        앞과 동일
    };

    return (
        <Container>
            {title && (
                <Title>{title}</Title>
            )}
            {
                slide &&
                <Wrapper><Slider {...settings}>{children}</Slider></Wrapper>
            }
            {
                !slide &&
                <Grid>{children}</Grid>
            }
        </Container>
    );
};

여기서는 Slider 태그 부분에 주목해야 합니다.

react-slick에서 자동적으로 Slider 태그를 제공해주므로 우리는 그저 가져다 쓰면서 settings를 props로 주게 되면 안에서 나열되는 html의 항목들은 자동적으로 슬라이드화 되게 됩니다.

profile
배워서 공유하기

0개의 댓글