LoginSignup
6
3

More than 1 year has passed since last update.

react-responsiveの使い方

Posted at

はじめに

npmのreact-responsiveパッケージを使うと、Reactでのレスポンシブ対応が簡単にできることが分かったので、その使用方法について勉強したことを自分の備忘録として残しておきます。

パッケージのインストール

ターミナル
% npm i react-responsive
...
...
...
% npm list | grep responsive
├── react-responsive@9.0.0-beta.6

With Hooks
Hooks is a new feature available in 8.0.0!

とnpmのページに書いてあるように、8.0.0以上のバージョンではhooksとして使えるようになりました。

使い方

index.tsx
import { useMediaQuery } from 'react-responsive'

const ResponsiveTest = () => {
  const isDesktop: boolean = useMediaQuery({ query: '(min-width: 768px)' })

  return (
    <>
      {/* 768px以上の時は、デスクトップ用のコンポーネントを表示 */}
      {isDesktop && <ForDesktopComponent />}
      {/* 768px未満の時は、 モバイル用のコンポーネントを表示 */}
      {!isDesktop && <ForMobileComponent />}
    </>
  )
}

このように、ユーザーが使用するデバイスの幅によってboolean値を取得でき、それに応じて表示するコンポーネントを切り替えられるようになっています。
また、

To make things more idiomatic to react, you can use camel-cased shorthands to construct media queries.

とあるように、キャメルケースを使った短縮形でメディアクエリを書くこともできます。

index.tsx
const isDesktop: boolean = useMediaQuery({ minWidth: 768 })

そしてこんな書き方も紹介されていました。

index.tsx
import { useMediaQuery } from 'react-responsive'

const Desktop = ({ children }) => {
  const isDesktop = useMediaQuery({ minWidth: 768 })
  return isDesktop ? children : null
}
const Mobile = ({ children }) => {
  const isMobile = useMediaQuery({ maxWidth: 767 })
  return isMobile ? children : null
}

const ResponsiveTest = () => (
  <div>
    <Desktop>パソコン</Desktop>
    <Mobile>スマートフォン</Mobile>
  </div>
)

export default ResponsiveTest;

まとめ

レスポンシブWebデザインを実現するためのメディアクエリをhooksを使って書けるのは非常に便利だと思いました。他にも、自動的に検出されるものとは異なるデバイス設定でコンポーネントをレンダリングする必要がある時、例えば、これらの設定が検出されないNode環境(SSR)やテストの際には、device propというのを使ってデバイスを強制的に指定することもできるそうです。
間違い等ありましたらご指摘お願いいたします。

6
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
6
3