Frontend/React

[React] 라이브러리 없이 Div Slideshow 구현하기

YERIEL_염주둥 2021. 4. 30. 08:45
728x90

메인 화면에 주요 컨텐츠 Image와 약간에 설명이 있는 div를 slideshow로 보여주고 싶어서 찾아보니 custom hook을 사용하거나 다양한 library를 이용하는 코드들이 대부분이었다.

사실 library로 손쉽게 구현하고 싶었으나 library를 더 추가하고 싶은 마음이 없어서 조금더 찾아보니 W3에서 html와 javascript로 작성해준 slideshow 코드를 발견했다.

www.w3schools.com/w3css/w3css_slideshow.asp

 

W3.CSS Slideshow

Displaying a manual slideshow with W3.CSS is very easy. First, set the slideIndex to 1. (First picture) Then call showDivs() to display the first image. When the user clicks one of the buttons call plusDivs(). The plusDivs() function subtracts one or  add

www.w3schools.com

react로 바꾸는거야 어렵지 않지ㅋㅋ (귀찮을 뿐이지...)

 

일단 Slideshow로 보여줄 div 부터 작성 시작

const SlideDiv = styled.div`
    display : ${prop=> prop.visibility};
    flex-direction : row;
    width : 100%;
    height : 300px;
    background-color : black;
    color : white;
    text-align : center;
`;
const SlideContent = styled.div`
    margin : auto;
    line-height : 5;
`;
const SlideImage = styled.img`
    padding : 10px;
    float : left;
    width : 40%;
    height : 100%;
`
const SlideTitle = styled.div`
    font-size: xx-large;
    text-transform: uppercase;
    margin-bottom : 20px;
`;

const SlideItem = (props) => {
    const {src, title, content, visivility} = props;

    return (
        <SlideDiv className="Slide-container" visibility={visibility}>
            <SlideImage  src={src} alt="w3slider"/>
            <SlideContent>
                <SlideTitle>
                    {title}
                </SlideTitle>
                <div>
                    {content}
                </div>
            </SlideContent>
        </SlideDiv>
    )
};

SlideDiv

 

그러고 나면 현재 Slide 위치와 이전 div, 다음 div로 넘어갈 수 있는 버튼 작성

const ButtonContainer = styled.div`
    text-align:center;
    margin-top:16px;
    margin-bottom:16px;
    font-size:18px;
    color:#fff;
    position:absolute;
    left:50%;
    bottom:0;
    transform:translate(-50%,0%);
    -ms-transform:translate(-50%,0%);
    width:100%;
`
const PrevButton = styled.div`
    cursor:pointer;
    float:left;
    &:hover{
        color : #eee;
    }
`
const NextButton = styled.div`
    cursor:pointer;
    float:right;
    &:hover{
        color : #eee;
    }
`
const Dot = styled.span`
    height:15px;
    width:15px;
    padding:0;
    margin : 0 5px;
    cursor : pointer;
    border-radius:50%;
    text-align:center;
    color:#fff;
    display:inline-block;
    border:1px solid #ccc;
    background-color:${prop=>prop.active ? '#fff' : 'transparent'};
    &: hover {
        color:#000!important;
        background-color:#fff;
    }
`

const ButtonBar = (props) => {
    const{slideIndex, slideLen, onNext, onPrev, onCurrent}=props;
    return (
        <ButtonContainer>
            <PrevButton onClick={()=>onPrev(-1)}>&#10094;</PrevButton>
            <NextButton onClick={()=>onNext(1)}>&#10095;</NextButton>
            {
                [...Array(slideLen)].map((_,index)=>(
                    <Dot active={slideIndex===index ? true:false} onClick={()=>onCurrent(index)} key={index}/>
                ))
            }

        </ButtonContainer>
    )
}

ButtonContainer

 

이제 버튼 기능 구현

    const [slideIndex, setSlideIndex] = useState(0)
    const showDivs = (idx)=>{
        const index = slideitems.length -1;
        if(-1<idx && idx===index){ 
            setSlideIndex(idx);
        } else if(idx < 0){ 
            setSlideIndex(slideitems.length-1);
        } else if (idx > index){
            setSlideIndex(0)
        } else if (idx < index){
            setSlideIndex(idx)
        }
    };
    const onPrev = ()=> {
        showDivs(slideIndex-1)
    }
    const onNext = ()=> {
        showDivs(slideIndex+1)
    }
    const currentDivs=(idx)=>{
        showDivs(idx)
    }

button 기능


예제로 찾은 훅이나 라이브러리 예제가 길어서 엄청 많은 페이지와 코드가 작성되면 훅이나 라이브러리를 사용하는 것이 효율적이지만 생각보다 짧은 코드로 구현할 수 있습니다.

반응형