hooks 생성
// useWheelScroll.js
import { useRef, useEffect, useCallback } from "react";
/**
* 마우스 휠 이벤트를 가로 스크롤로 변환하는 커스텀 훅
*
* @param {Object} options - 설정 옵션
* @param {number} [options.scrollSpeed=1] - 스크롤 속도 배수 (기본값: 1)
* @param {"auto" | "smooth"} [options.behavior="smooth"] - 스크롤 동작 (기본값: "smooth")
* @returns {Object} scrollRef: 스크롤 컨테이너에 할당할 ref
*/
export default function useWheelScroll({ scrollSpeed = 1, behavior = "smooth" } = {}) {
const scrollRef = useRef(null);
// onWheel 핸들러를 메모이제이션 (scrollSpeed와 behavior가 변경될 때만 새로 생성)
const onWheel = useCallback((event) => {
event.preventDefault();
if (scrollRef.current) {
scrollRef.current.scrollBy({
left: event.deltaY * scrollSpeed,
behavior,
});
}
}, [scrollSpeed, behavior]);
useEffect(() => {
const container = scrollRef.current;
if (!container) return;
// passive 옵션을 false로 설정하여 preventDefault 사용 가능하도록 함
container.addEventListener("wheel", onWheel, { passive: false });
// 컴포넌트 언마운트 또는 container가 변경될 때 이벤트 제거
return () => {
container.removeEventListener("wheel", onWheel, { passive: false });
};
}, [onWheel]);
return { scrollRef };
}
훅 사용 방법 > 스크롤 사용을 설정한 영역을 휠 스크롤(위, 아래)을 이용하여 횡 스크롤을 사용할 수 있다.
...
import useWheelScroll from "@/hooks/useWheelScroll";
const CustomComponent = () => {
...
const { scrollRef } = useWheelScroll({ scrollSpeed: 1.5, behavior: "smooth" });
return (
<div ref={scrollRef} className='overflow-x-auto'>
...
</div
);
};
export default RecentViewedStudySection;
'HowTo > React' 카테고리의 다른 글
[리액트] WSL에서 npm start 시 localhost:3000 실시간 업데이트 문제 해결 (0) | 2025.01.10 |
---|---|
[리액트] Pretendard 폰트 css @import로 적용하기 (0) | 2025.01.08 |
※ 쿠팡 파트너스 활동을 통해 일정액의 수수료를 제공받을 수 있습니다.