1. Resize 될 때마다 현재 window 의 width가 breakpoint 보다 up 인지 down 인지 물어보는 hook
- input : 없음
- output
- breakpoints : up / down 메소드를 가지고 있는 객체
useResizeBreakpoints.ts
- 코드
import { useState, useEffect } from "react";
interface GridBreakpoints {
xs: number;
sm: number;
md: number;
lg: number;
xl: number;
xxl: number;
}
interface Breakpoints {
up: (bp: keyof GridBreakpoints) => boolean;
down: (bp: keyof GridBreakpoints) => boolean;
}
interface UseResizeBreakpointsResult {
breakpoints: Breakpoints;
}
export const useResizeBreakpoints = (): UseResizeBreakpointsResult => {
const gridBreakpoints: GridBreakpoints = {
xs: 0,
sm: 576,
md: 768,
lg: 992,
xl: 1200,
xxl: 1540,
};
const [width, setWidth] = useState<number>(window.innerWidth);
const [height, setHeight] = useState<number>(window.innerHeight);
const [breakpoints, setBreakpoints] = useState<Breakpoints>({
up: (bp) => width >= gridBreakpoints[bp],
down: (bp) => width < gridBreakpoints[bp],
});
const updateDimensions = () => {
setWidth(window.innerWidth);
setHeight(window.innerHeight);
};
useEffect(() => {
window.addEventListener("resize", updateDimensions);
return () => window.removeEventListener("resize", updateDimensions);
}, []);
useEffect(() => {
setBreakpoints({
up: (bp) => width >= gridBreakpoints[bp],
down: (bp) => width < gridBreakpoints[bp],
});
}, [width]);
return { breakpoints };
};
MyComponent.tsx
- 사용하는 컴포넌트 코드
const { breakpoints } = useResizeBreakpoints();
...
return (
...
{breakpoints.down("sm") ? <div>SM 사이즈보다 작을때 </div> : <div>SM 사이즈보다 클때 </div>}
...
)
- 화면
- window 사이즈가 breakPoint 에서 sm 사이즈 보다 클 때
- window 사이즈가 breakPoint 에서 sm 사이즈 보다 클 때