import React from "react";
import styled from "styled-components";
const Container = styled.div`
display: flex;
align-items: center;
max-width: 500px;
width: 100%;
overflow-x: auto; 👈 중요
& .item {
display: flex;
justify-content: center;
align-items: center;
width: 100px;
height: 100px;
background-color: #e7e8e9;
flex-shrink: 0; 👈 중요
margin: 0 10px 0 0;
}
`;
function Swipe() {
return (
<Container>
<div className="item">1</div>
<div className="item">2</div>
<div className="item">3</div>
<div className="item">4</div>
<div className="item">5</div>
<div className="item">6</div>
<div className="item">7</div>
<div className="item">8</div>
<div className="item">9</div>
</Container>
);
}
flex
는 세 가지 속성을 갖는데, flex-grow
, flex-shrink
, flex-basis
이렇게 갖습니다.
축약형으로 flex: grow shrink basis
를 입력 받습니다.
코드 항목
에서 flex-grow를 추가해봤습니다.
const Container = styled.div`
...
& .item {
flex: 1; 👈 추가
...
}
`;
function Swipe() {
return ...
}
className이 item인 모든 element가 동일한 크기로 줄어들었습니다.
flex-grow
를 양수로 지정하면 항목 별로 주축 방향 크기가flex-basis
값 이상으로 늘어날 수 있게 됩니다.
flex-shrink는 다음과 같습니다.
const Container = styled.div`
...
& .item {
flex: 1; 👈 제거
flex-shrink: 0;
...
}
`;
function Swipe() {
return ...
}
다시 정상적으로 나오는 것을 볼 수 있습니다.
flex-shrink
는 주축의 공간이 부족할 때 각 항목의 크기를 줄이는 방법을 정의합니다.
0
으로 두면 크기를 줄이지 않습니다.
다음과 같은 방법으로 PC에선 Slider
를 구현할 수 있습니다.
좌우 버튼을 클릭하면 이동하는 느낌처럼요.
const Container = styled.div`
display: flex;
align-items: center;
max-width: 500px;
width: 100%;
overflow-x: hidden; // 👈 PC에선 Slider로 전환
@media ${device.mobileL} { // 👈 425px 아래서는 Swipe로 전환
overflow-x: auto;
}
scroll-behavior: smooth; // 👈 Slider 좌우 이동 시 이동을 부드럽게
& .item {
display: flex;
justify-content: center;
align-items: center;
width: 100px;
height: 100px;
background-color: #e7e8e9;
flex-shrink: 0;
margin: 0 10px 0 0;
}
`;
--------------------------------------------------
const ref = useRef<HTMLDivElement>(null);
const toRight = (event: never) => {
ref.current!.scrollLeft += 250;
}
const toLeft = (event: never) => {
ref.current!.scrollLeft -= 250;
}
--------------------------------------------------
return (
<>
<Container ref={ref}>
<div className="item">...</div>
...
</Container>
<button onClick={toLeft}>left</button>
<button onClick={toRight}>right</button>
</>
)