useMobile フックは、アプリケーションがモバイルサイズのデバイスで表示されているかどうかを検出するための便利なユーティリティです。Material-UIのブレークポイントシステムを活用することで、Reactロジック内で直接レスポンシブなレイアウトやコンポーネントを作成するのに役立ちます。
仕組み
内部では、useMobileはMaterial-UIのuseThemeとuseMediaQueryフックを使用します。現在の画面幅をテーマで定義されたブレークポイントと比較し、ビューポートが「モバイル」に該当するかどうかを判断します。
基本的な使用法
以下は、useMobileフックを使用してコンテンツを条件付きでレンダリングする簡単な例です。
ResponsiveComponent.tsx
import { useMobile } from '@blocklet/payment-react';
import { Typography, Box } from '@mui/material';
function ResponsiveComponent() {
const { isMobile, mobileSize } = useMobile();
return (
<Box p={2}>
<Typography variant="h5">
Responsive Content
</Typography>
{
isMobile ? (
<Typography>
This is the mobile view. The screen is {mobileSize} or smaller.
</Typography>
) : (
<Typography>
This is the desktop view. The screen is wider than {mobileSize}.
</Typography>
)
}
</Box>
);
}
export default ResponsiveComponent;パラメータ
useMobileフックは、ブレークポイントをカスタマイズするためのオプションのパラメータを受け付けます。
| 名前 | 型 | 説明 |
|---|---|---|
mobilePoint | 'md' | 'sm' | 'lg' | 'xl' | 'xs' | モバイルの閾値と見なすブレークポイントです。画面幅がこのポイント以下の場合、isMobileフラグはtrueになります。デフォルトは'md'です。 |
ブレークポイントのカスタマイズ
異なる値を渡すことで、ブレークポイントを簡単に変更できます。
CustomBreakpoint.tsx
import { useMobile } from '@blocklet/payment-react';
import { Typography } from '@mui/material';
function CustomBreakpointComponent() {
// 'sm' (small) 以下の画面をモバイルと見なす
const { isMobile } = useMobile('sm');
return (
<div>
{isMobile ? (
<Typography>Display for small screens</Typography>
) : (
<Typography>Display for medium and larger screens</Typography>
)}
</div>
);
}
export default CustomBreakpointComponent;戻り値
このフックは、以下のプロパティを持つオブジェクトを返します。
| キー | 型 | 説明 |
|---|---|---|
isMobile | boolean | 現在のビューポートの幅が指定されたmobilePointブレークポイント以下の場合はtrue、それ以外の場合はfalseです。 |
mobileSize | string | mobilePointブレークポイントのピクセル幅を表す文字列です (例: "900px")。 |