항목 추가하고 스크롤 — 필터 칩 패턴
사용자가 필터를 고르면 칩 바가 늘어나고, 새 칩은 오른쪽 끝 너머에 숨지 않고 화면에 나타나야 합니다. 함정은, 아직 렌더링되지 않은 요소로는 스크롤할 수 없다는 점. 이 예제는 작업을 클릭 핸들러와 이펙트로 나눕니다.
필터 추가를 클릭 — 칩이 끝에 나타나고 행이 스크롤해 보여줍니다. x는 칩을 제거합니다.
동작 방식
메뉴는 apiRef를 받아 컴포넌트 트리 밖에 완전한 API를 노출합니다. addItem은 두 가지를 합니다. 새 id를 lastAdded ref에 저장하고, 항목을 state에 추가합니다. 여기서 의도적으로 스크롤하지 않습니다 — 그 시점에 칩은 state일 뿐, DOM이 아니기 때문입니다.
스크롤을 이펙트에 두는 이유
getItemElementById는 DOM에서 항목을 찾으므로, 스크롤은 React가 새 항목을 커밋한 뒤에만 가능합니다. items를 키로 한 useEffect가 정확히 그 시점에 실행되어 lastAdded를 읽고 지운 뒤 apiRef.current.scrollToItem(el, ’smooth’, ’end’)를 호출합니다. ref를 지우는 것이 중요합니다 — 다른 이유(선택, 화살표)의 재렌더링도 같은 이펙트에 도달하므로, 다시 스크롤해서는 안 됩니다.
참고
lastAdded는 state가 아니라 ref입니다. 쓰기 자체가 렌더링을 일으켜선 안 되며, 그 값은 바로 다음 이펙트 실행에만 의미가 있습니다.’end’는 새 칩을 행의 오른쪽 끝에 맞춥니다. 가운데에 두려면’center’도 같은 방식으로 동작합니다.- 여기의 화살표는
useLeftArrowVisible()과useRightArrowVisible()훅을 씁니다 —useIsVisible(’first’/’last’)쌍의 짧은 형태입니다. - 스크롤바는 라이브러리의
scroll-container클래스에 대한 일반 CSS로 숨깁니다. 스크롤 자체는 네이티브로 남습니다.
전체 소스
완전하고 복사-붙여넣기 가능 — 이것이 바로 그 파일입니다. 출처는, 이 라이브 편집 가능한 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 AddItemAndScrollToItExample() {
const [items, setItems] = 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 apiRef = React.useRef<publicApiType>(null);
// The id of the item added by the last click; empty on mount and after the
// scroll fires, so re-renders for other reasons don't scroll again.
const lastAdded = React.useRef<string | null>(null);
const addItem = () => {
const newId = getId(items.length);
lastAdded.current = newId;
setItems((currentItems) => currentItems.concat({ id: newId }));
};
// `getItemElementById` looks the item up in the DOM, so the scroll can only
// happen after React has rendered the new item — an effect keyed on `items`
// rather than a call inside the click handler.
React.useEffect(() => {
const newId = lastAdded.current;
if (!newId) {
return;
}
lastAdded.current = null;
const el = apiRef.current?.getItemElementById(newId);
if (el) {
apiRef.current?.scrollToItem(el, 'smooth', 'end');
}
}, [items]);
return (
<div>
<div>
<button onClick={addItem} data-testid="add-item">
Add item
</button>
</div>
<NoScrollbar>
<ScrollMenu
LeftArrow={LeftArrow}
RightArrow={RightArrow}
onWheel={onWheel}
apiRef={apiRef}
>
{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>
</div>
);
}
export default AddItemAndScrollToItExample;
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',
},
});
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();
}
}