useMobile


The useMobile hook is a convenient utility for detecting if the application is being viewed on a mobile-sized device. It helps in creating responsive layouts and components directly within your React logic by leveraging Material-UI's breakpoint system.

How It Works#

Internally, useMobile uses Material-UI's useTheme and useMediaQuery hooks. It checks the current screen width against the theme's defined breakpoints to determine if the viewport qualifies as "mobile".

Basic Usage#

Here's a simple example of how to use the useMobile hook to conditionally render content.

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>
  );
}

See all 2 lines

Parameters#

The useMobile hook accepts an optional parameter to customize the breakpoint.

Name

Type

Description

mobilePoint

'md' | 'sm' | 'lg' | 'xl' | 'xs'

The breakpoint to consider as the mobile threshold. The isMobile flag will be true if the screen width is at or below this point. Defaults to 'md'.

Customizing the Breakpoint#

You can easily change the breakpoint by passing a different value.

CustomBreakpoint.tsx

import { useMobile } from '@blocklet/payment-react';
import { Typography } from '@mui/material';

function CustomBreakpointComponent() {
  // Consider 'sm' (small) screens and below as mobile
  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;

Return Value#

The hook returns an object with the following properties:

Key

Type

Description

isMobile

boolean

true if the current viewport width is less than or equal to the specified mobilePoint breakpoint, otherwise false.

mobileSize

string

A string representing the pixel width of the mobilePoint breakpoint (e.g., "900px").