모바일에서 화살표 숨기기 — 작은 화면의 터치 전용 스크롤
휴대폰에서 열거나 DevTools에서 터치 에뮬레이션을 켜세요 — 화살표가 사라지고 스와이프가 모든 일을 합니다.
데모가 화살표를 숨기는 방법
LeftArrow와 RightArrow는 선택적 프로퍼티입니다 — undefined를 넘기면 슬롯이 전혀 렌더링되지 않아, CSS로 숨길 것도, 탭 순서에 남을 버튼도 없습니다. 전환은 이펙트의 matchMedia(’(pointer: coarse)’) 확인입니다. 서버는 포인터 종류를 알 수 없으므로, 첫 페인트는 화살표를 넣은 데스크톱 우선이고, 거친 포인터가 확인되면 하이드레이션이 그것을 제거합니다. change 리스너가 라이브로 유지합니다 — DevTools 장치 에뮬레이션은 새로고침 없이 뒤집습니다.
스토리가 터치에서 하는 일
스토리의 useSwipe 훅은 자유 패닝을 페이지 넘김으로 바꿉니다. 커링된 onTouchStart, onTouchMove, onTouchEnd 프로퍼티는 각각 API 객체를 받습니다. start는 끝 좌표를 리셋하고 targetTouches[0].clientX를 기록하며, move는 그것을 추적하고, end는 이동 거리를 잽니다. minSwipeDistance(20px)를 넘으면 apiObj.scrollPrev()나 apiObj.scrollNext()를 호출합니다 — 손가락 속도와 무관하게 스와이프마다 스무스하게 한 페이지입니다.
네이티브 터치 스크롤 억제
페이지 넘김이 유일한 움직임이 되려면 브라우저 자체의 패닝을 멈춰야 하고, React 18+는 touchmove 리스너를 패시브로 등록해 preventDefault가 무시됩니다. 스토리의 이펙트는 apiRef(ref.current.scrollContainer.current)를 통해 실제 스크롤 요소에 도달해 { passive: false }로 자신의 리스너를 붙입니다. 그곳에서 호출이 동작합니다.
참고
- SSR 기본값은 의도적으로 고르세요. 화살표를 먼저 렌더링하는 것은 크롤러와 데스크톱 사용자에게 유리하고, 터치 장치는 하이드레이션 직후 그것을 잃습니다.
(pointer: coarse)는 화면 크기가 아니라 입력을 대상으로 합니다 — 좁은 데스크톱 창은 화살표를 유지하고, 태블릿은 그렇지 않습니다.- 화살표만 숨기고 네이티브 스와이프를 유지하고 싶다면(데모의 동작), 스토리의
touchmove이펙트를 건너뛰세요 — 자유 패닝과 숨은 화살표는 잘 공존합니다. - 터치 임계값은 20px, 데스크톱 플릭의 50px에 대비됩니다 — 마우스 변형은 swipe-on-desktop 예제를 보세요.
전체 소스
완전하고 복사-붙여넣기 가능 — 이것이 바로 그 파일입니다. 출처는, 이 라이브 편집 가능한 Storybook 버전.
import 'react-horizontal-scrolling-menu/dist/styles.css';
import styled from '@emotion/styled';
import React from 'react';
import {
type publicApiType,
ScrollMenu,
VisibilityContext,
} from 'react-horizontal-scrolling-menu';
export function MobileSwipeOnly() {
const [items] = React.useState(() => getItems());
const [selected, setSelected] = React.useState<string[]>([]);
const isItemSelected = (id: string): boolean =>
!!selected.find((el) => el === id);
const handleItemClick = (itemId: string) => {
const itemSelected = isItemSelected(itemId);
setSelected((currentSelected: string[]) =>
itemSelected
? currentSelected.filter((el) => el !== itemId)
: currentSelected.concat(itemId),
);
};
const { onTouchEnd, onTouchMove, onTouchStart } = useSwipe();
const ref = React.useRef<publicApiType>(null);
// React 18+ attaches touchmove listeners as passive, so preventDefault only
// works from a non-passive listener added manually to the scroll container.
React.useEffect(() => {
const onTouchMove = (ev: TouchEvent) => {
ev.preventDefault();
};
const node = ref.current?.scrollContainer.current;
node?.addEventListener('touchmove', onTouchMove, { passive: false });
return () => node?.removeEventListener('touchmove', onTouchMove);
}, [ref]);
return (
<NoScrollbar>
<ScrollMenu
LeftArrow={LeftArrow}
RightArrow={RightArrow}
onWheel={onWheel}
onTouchEnd={onTouchEnd}
onTouchMove={onTouchMove}
onTouchStart={onTouchStart}
apiRef={ref}
>
{items.map(({ id }) => (
<Card
title={id}
itemId={id} // NOTE: itemId is required for track items
key={id}
onClick={() => handleItemClick(id)}
selected={isItemSelected(id)}
/>
))}
</ScrollMenu>
</NoScrollbar>
);
}
export default MobileSwipeOnly;
export const useSwipe = () => {
const [touchStart, setTouchStart] = React.useState(0);
const [touchEnd, setTouchEnd] = React.useState(0);
// the required distance between touchStart and touchEnd to be detected as a swipe
const minSwipeDistance = 20;
const onTouchStart = () => (ev: React.TouchEvent) => {
setTouchEnd(0);
setTouchStart(ev.targetTouches[0].clientX);
};
const onTouchMove = () => (ev: React.TouchEvent) => {
setTouchEnd(ev.targetTouches[0].clientX);
};
const onTouchEnd = (apiObj: publicApiType) => () => {
if (!touchStart || !touchEnd) return false;
const distance = touchStart - touchEnd;
const isSwipe = Math.abs(distance) > minSwipeDistance;
const isLeftSwipe = distance < minSwipeDistance;
if (isSwipe) {
if (isLeftSwipe) {
apiObj.scrollPrev();
} else {
apiObj.scrollNext();
}
}
};
return { onTouchStart, onTouchEnd, onTouchMove };
};
const NoScrollbar = styled('div')({
'&': {
position: 'relative',
},
'& .react-horizontal-scrolling-menu--scroll-container::-webkit-scrollbar': {
display: 'none',
},
'& .react-horizontal-scrolling-menu--scroll-container': {
scrollbarWidth: 'none',
'-ms-overflow-style': 'none',
},
});
function LeftArrow() {
const visibility = React.useContext<publicApiType>(VisibilityContext);
const disabled = visibility.useLeftArrowVisible();
return (
<Arrow
disabled={disabled}
onClick={() => visibility.scrollPrev()}
testId="left-arrow"
>
Left
</Arrow>
);
}
function RightArrow() {
const visibility = React.useContext<publicApiType>(VisibilityContext);
const disabled = visibility.useRightArrowVisible();
return (
<Arrow
disabled={disabled}
onClick={() => visibility.scrollNext()}
testId="right-arrow"
>
Right
</Arrow>
);
}
function Arrow({
children,
disabled,
onClick,
className,
testId,
}: {
children: React.ReactNode;
disabled: boolean;
onClick: VoidFunction;
className?: string;
testId: string;
}) {
return (
<ArrowButton
disabled={disabled}
onClick={onClick}
className={'arrow' + `-${className}`}
data-testid={testId}
>
{children}
</ArrowButton>
);
}
const ArrowButton = styled('button')((props) => ({
cursor: 'pointer',
display: 'flex',
flexDirection: 'column',
justifyContent: 'center',
marginBottom: '2px',
opacity: props.disabled ? '0' : '1',
userSelect: 'none',
borderRadius: '6px',
borderWidth: '1px',
}));
function Card({
onClick,
selected,
title,
itemId,
}: {
onClick: (context: publicApiType) => void;
selected: boolean;
title: string;
itemId: string;
}) {
const visibility = React.useContext<publicApiType>(VisibilityContext);
const isVisible = visibility.useIsVisible(itemId, true);
return (
<CardBody
data-cy={itemId}
onClick={() => onClick(visibility)}
onKeyDown={(ev: React.KeyboardEvent) => {
ev.code === 'Enter' && onClick(visibility);
}}
data-testid="card"
role="button"
tabIndex={0}
className="card"
visible={isVisible}
selected={selected}
>
<div className="header">
<div>{title}</div>
<div className="visible">visible: {JSON.stringify(isVisible)}</div>
<div className="selected">selected: {JSON.stringify(!!selected)}</div>
</div>
<div className="background" />
</CardBody>
);
}
const CardBody = styled('div')<{ selected?: boolean; visible?: boolean }>(
(props) => ({
border: '1px solid',
display: 'inline-block',
margin: '0 10px',
width: '160px',
userSelect: 'none',
borderRadius: '8px',
overflow: 'hidden',
'& .header': {
backgroundColor: 'white',
},
'& .visible': {
backgroundColor: props.visible ? 'transparent' : 'gray',
},
'& .background': {
backgroundColor: props.selected ? 'green' : 'bisque',
height: '200px',
},
}),
);
const getId = (index: number) => `${'test'}${index}`;
const getItems = () =>
Array(10)
.fill(0)
.map((_, ind) => ({ id: getId(ind) }));
function onWheel(apiObj: publicApiType, ev: React.WheelEvent): void {
// NOTE: no good standart way to distinguish touchpad scrolling gestures
// but can assume that gesture will affect X axis, mouse scroll only Y axis
// of if deltaY too small probably is it touchpad
const isThouchpad = Math.abs(ev.deltaX) !== 0 || Math.abs(ev.deltaY) < 15;
if (isThouchpad) {
ev.stopPropagation();
return;
}
if (ev.deltaY < 0) {
apiObj.scrollNext();
} else {
apiObj.scrollPrev();
}
}