본문 바로가기
JavaScript/React

[React] 라이브러리 없이 자동 슬라이드 구현

by 비븽 2024. 1. 10.

✨ 구현된 모습

쿨타임은 4초다

 

새 프로젝트에서 배너를 만들게 되었는데 라이브러리 없이도 할 수 있을 것 같아서 간단하게 만들어 보았다!

 

일단 가볍게 시도해본거라서 무한 슬라이드까진 아니고, 마지막 배너라면 다시 처음으로 돌아가게끔 설계했다. 이게 문제점이 배너가 4개면 괜찮은데 배너가 2개뿐이거나 혹은 배너가 아주 많을 때는 돌아가는게 너무 어지러워서...😵‍💫  조만간 무한 슬라이드로 수정하지 않을까 싶다.

 

👩‍💻 전체 코드

CSS

const BannerArea = styled.div`
  width: 100%;
  aspect-ratio: 5/2; // 종횡비
  position: relative;
  margin-bottom: 2rem;
`;
const BannerList = styled.div`
  display: flex;
  position: absolute;
  top: 0;
  left: ${(props) => (props.count === 0 ? "0%" : props.count * -100 + "%")};
  width: ${(props) =>
    props.length === 0 ? "0%" : props.length * 100 + "%"}; // list길이 따라
  height: 100%;
  transition: 1s; // 애니메이션
`;
const Banner = styled.div`
  width: 100%;
  height: 100%;
  object-fit: cover;
  overflow: hidden;
  cursor: pointer;
`;
const Banner_Pic = styled.img`
  width: 100%;
`;

JS

const Home = () => {
  const banner_list = [1, 2, 3, 4];
  const [count, setCount] = useState(0);
  useEffect(() => {
    const timer = setTimeout(() => {
      if (count === banner_list.length - 1) {
        setCount(0);
      } else {
        setCount(count + 1);
      }
    }, 4000);
    return () => clearTimeout(timer);
  }, [count]);

  return (
    <Container>
      <BannerArea>
        <CountArea>
          {count + 1} / {banner_list.length}
        </CountArea>

        <BannerList count={count} length={banner_list.length}>
          {banner_list.map((list, idx) => {
            return (
              <Banner key={idx}>
                <Banner_Pic src={require("../img/Banner1.jpg")} />
              </Banner>
            );
          })}
        </BannerList>
      </BannerArea>
    </Container>
  );
};

export default Home;

 

 

banner_list는 배너의 리스트가 담긴 배열이고, count는 사용자가 보는 배너의 idx다.

 

'JavaScript > React' 카테고리의 다른 글

d  (0) 2024.03.19
[React] input type date 아이콘 커스텀  (0) 2023.12.27
[React] 자동 무한 롤링 슬라이드 구현  (0) 2023.12.25
[React] 로딩바 구현  (0) 2023.12.18
[React] 간단한 알림창 모달  (0) 2023.12.18