【TypeScript + React hooks】CSSに合わせてresponsiveにするカスタムhookの実装例
はじめに
単一のCSSファイルの中でresponsiveにしていて、JS側でもデザインに合わせて挙動を変えたくなったので、その時のメモ。
実装例
windowのサイズが変わった際には再描画する必要があるので、カスタムhook内でresize eventをlistenしてやれば良い。
import React from 'react'; export default (): boolean => { const [isPC, setIsPC] = React.useState(false); const evaluateIsPC = React.useCallback(() => { setIsLaptop(window.innerWidth >= 980); }, []); React.useLayoutEffect(() => { evaluateIsPC(); window.addEventListener('resize', evaluateIsPC); return (): void => { window.removeEventListener('resize', evaluateIsPC); }; }); return isPC; };
使い方
const isPC = useResponsive();
として、isPCの値に応じて場合分けをする。
問題点
CSSとJSでbreakpointの設定がDRYにならない。