본문 바로가기

react-shop-web/front & back

이미지 슬라이더 만들기

이미지를 여러개 업로드 했을 때 LandingPage에서 자동으로 여러 개 업로드 했던 이미지들을 슬라이더처럼 보여주도록 구현하자.

 

https://ant.design/components/carousel

 

Carousel - Ant Design

A carousel component. Scales with its container. When To Use When there is a group of content on the same level.When there is insufficient content space, it can be used to save space in the form of a revolving door.Commonly used for a group of pictures/car

ant.design

 

Card 컴포넌트 안에 있는 cover 부분에 Carousel 컴포넌트를 넣어주면 된다.

하지만 이렇게 넣어주면 코드가 너무 더러워 지니까 이미지 슬라이더 부분을 컴포넌트로 만들어서 넣어주자. 

 

utils 폴더 안에 ImageSlider.js 파일을 만들어주자. 

import React from 'react'
import {Carousel} from 'antd'


function ImageSlider(props) {
  return (
      <div>
            <Carousel autoplay>
                  {props.images.map((image, index) => (
                    <div key={index}>
                          <img style={{ width: '100%', maxHeight: '150px'}} src={process.env.REACT_APP_SERVER + `/${image}`} />
                      </div>
                    ))}
            </Carousel>
      </div>
  )
} 

export default ImageSlider
import axios from 'axios';
import React, { useEffect, useState } from 'react'
import {Icon, Col, Row, Card, Carousel} from 'antd'
import Meta from 'antd/lib/card/Meta';
import ImageSlider from '../../utils/ImageSlider'


function LandingPage() {

    const [Products, setProducts] = useState([])

    useEffect(() => {
        // 원래라면 필터 기능을 위해 axios에 요청할 때 body 객체를 함께 보내주는데 현재 단계에선 모든
        // 상품을 갖고오기 때문에 아직까진 필요없다.

        axios.post('/api/product/products') 
            .then(response => {
                if(response.data.success){
                    setProducts(response.data.productInfo)
                }else {
                    alert('상품들을 갖고오는데 실패')
                }
            })
    },[])

    const renderCards = Products.map((product, index) => {
        return (
            <Col lg={6} md={8} xs={24} key={index}>
                <Card
                    cover={<ImageSlider images={product.images} />}>
                    <Meta
                        title={product.title} 
                        description={`${product.price}`}
                    />
                </Card>
            </Col>
        )
    })

    return (
        <div style={{ width: '75%', margin: '3rem auto' }}>
            <div style={{textAlign: 'center'}}>
                <h2>Let's Travel Anywhere <Icon type="rocket"/></h2>
            </div>

            {/* Filter */}

            {/* Search */}
        
            <Row gutter={[16, 16]}>
                {renderCards}
            </Row>

            <div style={{display:'flex', justifyContent: 'center'}}>
                <button>더보기</button>
            </div>
        </div>
    )
}

export default LandingPage