LoginSignup
3
3

More than 3 years have passed since last update.

react-useのuseMediaを使ったレスポンシブ対応

Posted at

react-use はhooksにあると便利なものがそろっているライブラリで、スター数的にもそれなりに使われてそうな感じがするので個人で作るときには結構導入してます

const.ts
export const mediaQuery = Object.freeze({
  xs: '(min-width: 36rem)',
  sm: '(min-width: 48rem)',
  md: '(min-width: 62rem)',
  lg: '(min-width: 75rem)',
})

上記のようにモバイルファーストっぽく書いた場合

const mq = {
  match: [
    useMedia(mediaQuery.lg),
    useMedia(mediaQuery.md),
    useMedia(mediaQuery.xs),
  ],
  colmuns: [4, 3, 2],
}
const colmunIndex = mq.match.findIndex((_) => _)
// どれともマッチしない場合は1に
const colmunLength = colmunIndex === -1 ? 1 : mq.colmuns[colmunIndex]

こんな感じで書くと良さそう。毎回書くので自分のコピペ用として

3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3