화살표를 메뉴 아래에 — 또는 레이아웃 어디에든
화살표는 내장 크롬이 아니라 여러분이 전달하는 컴포넌트입니다. 그래서 배치는 라이브러리 설정이 아니라 레이아웃 결정입니다. 이 예제는
LeftArrow나 RightArrow를 전혀 전달하지 않고, 두 버튼을 행 아래의 Footer 슬롯, 일반 콘텐츠 옆에 렌더링합니다.화살표는 행 아래에 있습니다 — 같은 VisibilityContext를 읽으므로, 끝에서는 여전히 비활성화됩니다.
동작 방식
ScrollMenu는 Footer 컴포넌트를 받아 스크롤 컨테이너 아래, 항목들과 같은 VisibilityContext.Provider 안에 렌더링합니다. 스토리의 푸터는 텍스트와 두 개의 화살표 버튼을 담은 평범한 flex div입니다. 컨텍스트가 닿으므로 각 버튼은 React.useContext(VisibilityContext)를 호출해 사이드 슬롯에서 얻는 것과 정확히 같은 API를 받습니다 — 화살표 자체는 아무것도 변하지 않습니다.
화살표 상태, 늘 그대로
useLeftArrowVisible()과 useRightArrowVisible()은 행이 이미 그 끝에 있는지 보고합니다. 스토리는 결과를 disabled에 매핑하고 버튼을 페이드아웃합니다. 클릭은 scrollPrev()와 scrollNext()를 호출합니다. 이 중 어느 것도 버튼이 어디에 마운트되었는지 알지도, 신경 쓰지도 않습니다.
참고
Header는 행 위쪽의 거울 슬롯으로, 계약은 같습니다.- 사이드의
LeftArrow/RightArrow프로퍼티는 미리 배치된 변형일 뿐입니다 — 같은 화살표 컴포넌트가 어느 위치에서든 동작합니다. - 푸터는 화살표 전용이 아닙니다.
VisibilityContext를 읽는 컴포넌트라면 거기서 완전한 API를 얻습니다. - 스토리의
onWheel핸들러는 마우스 휠로 페이지를 넘기고, 터치패드 제스처는 네이티브 스크롤에 남겨 둡니다.
전체 소스
완전하고 복사-붙여넣기 가능 — 이것이 바로 그 파일입니다. 출처는, 이 라이브 편집 가능한 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 BottomArrows() {
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),
);
};
return (
<NoScrollbar>
<ScrollMenu Footer={Arrows} onWheel={onWheel}>
{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 BottomArrows;
const NoScrollbar = styled('div')({
'& .react-horizontal-scrolling-menu--scroll-container::-webkit-scrollbar': {
display: 'none',
},
'& .react-horizontal-scrolling-menu--scroll-container': {
scrollbarWidth: 'none',
'-ms-overflow-style': 'none',
},
});
const Arrows = () => (
<div
style={{
width: '100%',
display: 'flex',
justifyContent: 'center',
}}
>
Some other content
<div style={{ marginLeft: '10px', display: 'flex' }}>
<LeftArrow /> <RightArrow />
</div>
</div>
);
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();
}
}