react-device-detectでPC/モバイル判定を行う

公開日時

react-device-detectを使うと手軽にPC/モバイルの判定ができる。

  • インストール
yarn add react-device-detect
  • 使い方

isMobile を使うとモバイル判定ができる

import { isMobile } from "react-device-detect"

export const Some = () => {
  return (
    <>
      <p>some content</p>

      {isMobile ? (
        <p>this is mobile only content</p>
      ) : (
        <p>this is pc only content</p>
      )}
    </>
  )
}

BrowserView, MobileView を使うとPC, モバイルの場合のみchildrenのコンポーネントを表示することもできる。

import { BrowserView, MobileView } from "react-device-detect"

export const Some = () => {
  return (
    <>
      <p>some content</p>

      <MobileView>
        <p>this is mobile only content</p>
      </MobileView>

      <BrowserView>
        <p>this is pc only content</p>
      </BrowserView>
    </>
  )
}

Related #next.js

Next.js使用時にrecoil-persistのStorageを変更する

クライアント側で実行された場合のみstorageを指定するようにした

Next.jsで環境に応じて特定のページを非表示にする

NODE_ENVでredirectsを出し分けた

Next.jsで動的URLをRewriteする

next.config.jsにrewritesを追加

Next.js + typescriptでpathsのエイリアスがModule not foundになる

next.config.jsに追記する必要があった

Next.js + Algoliaで全文検索UIを実装する

react-instantsearchを利用