React js에서 이미지 슬라이더를 만드는 방법/React js에서 자동 이미지 슬라이더를 만드는 방법

React js에서 이미지 슬라이더를 만드는 방법/React js에서 자동 이미지 슬라이더를 만드는 방법

**1. 구성 요소를 만듭니다.

구성 요소를 나타내는 ImageSlider.js 및 ImageSliderAuto.js 파일을 만듭니다.

1) 이미지 슬라이더.js

import React, { useEffect, useState } from 'react';
import  './ImageSlider.css';

const ImageSlider = (props) => {
    const SliderProperty = {
        ImageNo: '',
        ImageName: '',
        ImageSrc: ''
    }

    const [sliderProperty, setSliderProperty] = useState(SliderProperty);

    const { ImageNo, ImageName, ImageSrc } = sliderProperty;

    const [count, setCount] = useState(0);


    const [animationCls, setAnimationCls] = useState('displayBlock fade');

    const PreClick = () => {

        setAnimationCls(() => ('displayNone fade'));
        const myTimeout = setTimeout(() => {
            setAnimationCls('displayBlock fade')
        }, 100);

        if (count > 0) {
            setCount((preCount) => preCount - 1);  
        }

        if (count === 0) {
            setCount(props.ImageData.length-1);
        }

    };

    const NextClick = () => {

        setAnimationCls(() => ('displayNone fade'));
        const myTimeout = setTimeout(() => {
            setAnimationCls('displayBlock fade')
        }, 100);

        if (count <= props.ImageData.length - 2) {
            setCount((preCount) => preCount + 1);           
        }

        if (count === props.ImageData.length-1) {
            setCount(0);
        }

    };

    useEffect(() => {

        setSliderProperty((previous) => ({ ...previous, ImageNo: props.ImageData[count].ImageNo, ImageName: props.ImageData[count].ImageName, ImageSrc: props.ImageData[count].ImageSrc }));

    }, [count]);
    return (
        <>
            <div className='slideshow-container '>


                <div className={animationCls}>
                    <div className="numbertext">{ImageNo}</div>
                    <img src={ImageSrc} style={{ width: '100%', height: '100%' }} alt="Img" />
                </div>

                <button className="prev" onClick={PreClick}>❮</button>
                <button className="next" onClick={NextClick}>❯</button>
                <div className="text">{ImageName}</div>
            </div>


            </>

        );
};

export default ImageSlider;


2)ImageSliderAuto.js

import React, { useEffect, useState } from 'react';
import './ImageSlider.css';

const ImageSliderAuto = (props) => {
    const SliderProperty = {
        ImageNo: '',
        ImageName: '',
        ImageSrc: ''
    }

    const [sliderProperty, setSliderProperty] = useState(SliderProperty);

    const { ImageNo, ImageName, ImageSrc } = sliderProperty;

    const [count, setCount] = useState(0);


    const [animationCls, setAnimationCls] = useState('displayBlock fade');



    const NextClick = () => {

        setAnimationCls(() => ('displayNone fade'));
        const myTimeout = setTimeout(() => {
            setAnimationCls('displayBlock fade')
        }, 100);

        if (count <= props.ImageData.length-1) {
            setCount(count+1);
        }

        if (count === props.ImageData.length-1) {
            setCount(0);
        }

    };

    useEffect(() => {

        setSliderProperty((previous) => ({ ...previous, ImageNo: props.ImageData[count].ImageNo, ImageName: props.ImageData[count].ImageName, ImageSrc: props.ImageData[count].ImageSrc }));

    }, [count]);



    useEffect(() => {

         const interval=  setInterval(() => {

            NextClick();

        }, props.SlideInterValTime);

        return () => clearInterval(interval);

    }, [count]);



    return (
        <>
            <div className='slideshow-container '>


                <div className={animationCls}>
                    <div className="numbertext">{ImageNo}</div>
                    <img src={ImageSrc} className='imageStyle' alt="Img" />
                </div>
                <div className="text">{ImageName}</div>
            </div>


        </>

    );
};

export default ImageSliderAuto;


3. .ImageSlider.css 파일 생성

.slideshow-container {
    width: 70%;
    position: relative;
    margin: auto;
    height:350px;
}
.imageStyle{
width: 100%;
height: 100%;
}
.prev, .next {
    cursor: pointer;
    position: absolute;
    top: 50%;
    width: auto;
    padding: 16px;
    margin-top: -22px;
    color: white;
    font-weight: bold;
    font-size: 18px;
    transition: 0.6s ease;
    border-radius: 0 3px 3px 0;
    user-select: none;
    border:none;
    background-color:transparent
}
.next {
    right: 0;
    border-radius: 3px 0 0 3px;
}
.prev:hover, .next:hover {
  background-color: rgba(0,0,0,0.8);
}

.displayNone{
    display:none;
}
.displayBlock {
    display: block;
}

.numbertext {
    color: #f2f2f2;
    font-size: 12px;
    padding: 8px 12px;
    position: absolute;
    top: 0;
}

.text {
    color: #f2f2f2;
    font-size: 15px;
    padding: 8px 12px;
    position: absolute;
    bottom: 13px;
    width: 100%;
    text-align: center;
    float: left;
}

/* Fading animation */
.fade {
    width: 100%;
    height: 100%;
    animation-name: fade;
    animation-duration: 1.5s;
}
@keyframes fade {
  from {opacity: .4} 
  to {opacity: 1}
}



3) App.js 파일에 컴포넌트(ImageSlider/ImageSliderAuto) 추가

import './App.css';
import ImageSlider from './component/ImageSlider';
import ImageSliderAuto from './component/ImageSliderAuto';
import { ImageData } from './json/JsonData';

function App() {
  return (
      <>
          <ImageSlider ImageData={ImageData}/><br/>
          <ImageSliderAuto ImageData={ImageData} SlideInterValTime={ 2000}/>
      </>

  );
}

export default App;
`



4) 이미지 세부 정보를 위한 Json 파일 생성

`import Img1 from '../img/img_mountains_wide.jpg'
import Img2 from '../img/img_nature_wide.jpg'
import Img3 from '../img/img_snow_wide.jpg'
import Img4 from '../img/img_band_ny.jpg'
export const ImageData = [
    {
        ImageNo:'1/4',
        ImageName: 'mountains',
        ImageSrc: Img1
    },
    {
        ImageNo: '2/4',
        ImageName: 'img_nature',
        ImageSrc: Img2
    },
    {
        ImageNo: '3/4',
        ImageName: 'img_snow',
        ImageSrc: Img3
    },
    {
        ImageNo: '4/4',
        ImageName: 'img_band_ny',
        ImageSrc: Img4
    }
];



잘했어요! 이제 웹 사이트를 위한 멋진 슬라이더가 생겼습니다!

좋아요나 댓글로 사랑을 전해주세요♥

참조 w3schools

Download Source Code from GitHub Repository

좋은 웹페이지 즐겨찾기