Skip to content

Instantly share code, notes, and snippets.

@yano3nora
Last active March 21, 2023 04:43
Show Gist options
  • Save yano3nora/04f52784ee9fd33b49739abf43ed0f87 to your computer and use it in GitHub Desktop.
Save yano3nora/04f52784ee9fd33b49739abf43ed0f87 to your computer and use it in GitHub Desktop.
[js: matchMedia] Using Media Query from JavaScript. #js
/**
* media query を満たすかどうか js で判定可能
*
* @link https://developer.mozilla.org/ja/docs/Web/API/Window/matchMedia
*/
if (window.matchMedia( "(min-width: 400px)" ).matches) {
/* ビューポートの幅が 400 ピクセル以上の場合のコードをここに */
} else {
/* ビューポートの幅は 400 ピクセル未満の場合のコードをここに */
}
/**
* resize 対応するなら mediaQueryList の
* change イベントを listen するといいみたい
*
* @link https://zenn.dev/no4_dev/articles/878f4afbff6668d4e28a-2
*/
const breakpoints = { sm: '365px', md: '768px', lg: '1024px' }
const [isWideDevice, setIsWideDevice] = useState(true)
/**
* 依存のない use effect で render 直後に window object から
* matchMedia で media query を判定させて、以降 break point の change を
* 監視して isWideDevice かどうかの状態を判定させている
*/
useEffect(() => {
const query = window.matchMedia(`(min-width: ${breakpoints.md})`)
const setIsWideDeviceOnChange = () => setIsWideDevice(query.matches)
setIsWideDeviceOnChange() // for init
query.addEventListener('change', setIsWideDeviceOnChange) // for resize
// for unmount
return () => query.removeEventListener('change', setIsWideDeviceOnChange)
}, [])
return <>
<div>hello!</div>
{
isWideDevice &&
<div>wide!</div>
}
</>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment