react-responsive vs react-device-detect vs react-media vs react-responsive-carousel
Web開発におけるレスポンシブデザインライブラリ
react-responsivereact-device-detectreact-mediareact-responsive-carousel類似パッケージ:

Web開発におけるレスポンシブデザインライブラリ

これらのライブラリは、異なるデバイスや画面サイズに応じて、Reactアプリケーションの表示を調整するために使用されます。これにより、ユーザーに最適な体験を提供し、アプリケーションの使いやすさを向上させます。特に、モバイルファーストのアプローチが重要視される現代のウェブ開発において、これらのライブラリは不可欠です。

npmのダウンロードトレンド

3 年

GitHub Starsランキング

統計詳細

パッケージ
ダウンロード数
Stars
サイズ
Issues
公開日時
ライセンス
react-responsive1,022,5657,18056.6 kB51年前MIT
react-device-detect02,93149.6 kB733年前MIT
react-media02,425-86年前MIT
react-responsive-carousel02,682188 kB5-MIT

機能比較: react-responsive vs react-device-detect vs react-media vs react-responsive-carousel

デバイス検出

  • react-device-detect:

    react-device-detectは、ユーザーのデバイス情報を検出するためのライブラリで、デスクトップ、タブレット、モバイルデバイスを識別できます。これにより、特定のデバイスに基づいて異なるコンポーネントを表示することが可能になります。特に、デバイスに応じた最適化が必要な場合に役立ちます。

メディアクエリの統合

  • react-media:

    react-mediaは、CSSのメディアクエリをReactコンポーネントに統合するためのライブラリです。これにより、画面サイズやデバイスの特性に応じて異なるコンポーネントを簡単に表示できます。レスポンシブデザインを実現するための強力なツールです。

レスポンシブレンダリング

  • react-responsive:

    react-responsiveは、異なるデバイスや画面サイズに基づいてコンポーネントを条件付きでレンダリングするためのシンプルなAPIを提供します。これにより、開発者はレスポンシブデザインを簡単に実装でき、ユーザー体験を向上させることができます。

カルーセル機能

  • react-responsive-carousel:

    react-responsive-carouselは、レスポンシブなカルーセルコンポーネントを提供するライブラリです。スライドショーや画像ギャラリーを簡単に作成でき、モバイルデバイスでも適切に表示されるように設計されています。ユーザーがコンテンツを視覚的に楽しむための便利な機能です。

使いやすさ

  • react-responsive:

    react-responsiveは、シンプルな構文でレスポンシブデザインを実現できるため、学習コストが低く、すぐに使い始めることができます。

  • react-device-detect:

    react-device-detectは、デバイスの検出を簡単に行えるため、開発者にとって使いやすいライブラリです。シンプルなAPIを提供し、迅速にデバイス情報を取得できます。

  • react-media:

    react-mediaは、メディアクエリをReactに統合するための直感的なインターフェースを提供し、開発者が迅速にレスポンシブデザインを実装できるようにします。

  • react-responsive-carousel:

    react-responsive-carouselは、スライダー機能を簡単に実装できるため、特にビジュアルコンテンツを扱うプロジェクトにおいて、迅速な開発が可能です。

選び方: react-responsive vs react-device-detect vs react-media vs react-responsive-carousel

  • react-responsive:

    レスポンシブデザインを簡単に実装したい場合は、react-responsiveを選択してください。このライブラリは、簡潔なAPIを提供し、異なるデバイスや画面サイズに基づいてコンポーネントを条件付きでレンダリングできます。

  • react-device-detect:

    デバイスの種類に応じて異なるコンポーネントを表示する必要がある場合は、react-device-detectを選択してください。このライブラリは、ユーザーのデバイス情報を簡単に取得でき、条件に応じたレンダリングを可能にします。

  • react-media:

    メディアクエリを使用して、異なる画面サイズに基づいてコンポーネントを条件付きで表示したい場合は、react-mediaを選択してください。このライブラリは、CSSのメディアクエリをReactコンポーネントに統合するのに役立ちます。

  • react-responsive-carousel:

    スライダーやカルーセルを実装したい場合は、react-responsive-carouselを選択してください。このライブラリは、レスポンシブなカルーセルコンポーネントを提供し、スライドショー機能を簡単に追加できます。

react-responsive のREADME

react-responsive NPM version Downloads

Information

Packagereact-responsive
DescriptionMedia queries in react for responsive design
Browser Version>= IE6*
Demo

The best supported, easiest to use react media query module.

Install

$ npm install react-responsive --save

Example Usage

With Hooks

Hooks is a new feature available in 8.0.0!

import React from 'react'
import { useMediaQuery } from 'react-responsive'

const Example = () => {
  const isDesktopOrLaptop = useMediaQuery({
    query: '(min-width: 1224px)'
  })
  const isBigScreen = useMediaQuery({ query: '(min-width: 1824px)' })
  const isTabletOrMobile = useMediaQuery({ query: '(max-width: 1224px)' })
  const isPortrait = useMediaQuery({ query: '(orientation: portrait)' })
  const isRetina = useMediaQuery({ query: '(min-resolution: 2dppx)' })

  return (
    <div>
      <h1>Device Test!</h1>
      {isDesktopOrLaptop && <p>You are a desktop or laptop</p>}
      {isBigScreen && <p>You have a huge screen</p>}
      {isTabletOrMobile && <p>You are a tablet or mobile phone</p>}
      <p>Your are in {isPortrait ? 'portrait' : 'landscape'} orientation</p>
      {isRetina && <p>You are retina</p>}
    </div>
  )
}

With Components

import MediaQuery from 'react-responsive'

const Example = () => (
  <div>
    <h1>Device Test!</h1>
    <MediaQuery minWidth={1224}>
      <p>You are a desktop or laptop</p>
      <MediaQuery minWidth={1824}>
        <p>You also have a huge screen</p>
      </MediaQuery>
    </MediaQuery>
    <MediaQuery minResolution="2dppx">
      {/* You can also use a function (render prop) as a child */}
      {(matches) =>
        matches ? <p>You are retina</p> : <p>You are not retina</p>
      }
    </MediaQuery>
  </div>
)

API

Using Properties

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

For a list of all possible shorthands and value types see https://github.com/yocontra/react-responsive/blob/master/src/mediaQuery.ts#L9.

Any numbers given as shorthand will be expanded to px (1234 will become '1234px').

The CSS media queries in the example above could be constructed like this:

import React from 'react'
import { useMediaQuery } from 'react-responsive'

const Example = () => {
  const isDesktopOrLaptop = useMediaQuery({ minWidth: 1224 })
  const isBigScreen = useMediaQuery({ minWidth: 1824 })
  const isTabletOrMobile = useMediaQuery({ maxWidth: 1224 })
  const isPortrait = useMediaQuery({ orientation: 'portrait' })
  const isRetina = useMediaQuery({ minResolution: '2dppx' })

  return <div>...</div>
}

Forcing a device with the device prop

At times you may need to render components with different device settings than what gets automatically detected. This is especially useful in a Node environment where these settings can't be detected (SSR) or for testing.

Possible Keys

orientation, scan, aspectRatio, deviceAspectRatio, height, deviceHeight, width, deviceWidth, color, colorIndex, monochrome, resolution and type

Possible Types

type can be one of: all, grid, aural, braille, handheld, print, projection, screen, tty, tv or embossed

Note: The device property always applies, even when it can be detected (where window.matchMedia exists).

import { useMediaQuery } from 'react-responsive'

const Example = () => {
  const isDesktopOrLaptop = useMediaQuery(
    { minDeviceWidth: 1224 },
    { deviceWidth: 1600 } // `device` prop
  )

  return (
    <div>
      {isDesktopOrLaptop && (
        <p>
          this will always get rendered even if device is shorter than 1224px,
          that's because we overrode device settings with 'deviceWidth: 1600'.
        </p>
      )}
    </div>
  )
}

Supplying through Context

You can also pass device to every useMediaQuery hook in the components tree through a React Context. This should ease up server-side-rendering and testing in a Node environment, e.g:

Server-Side Rendering
import { Context as ResponsiveContext } from 'react-responsive'
import { renderToString } from 'react-dom/server'
import App from './App'

...
  // Context is just a regular React Context component, it accepts a `value` prop to be passed to consuming components
  const mobileApp = renderToString(
    <ResponsiveContext.Provider value={{ width: 500 }}>
      <App />
    </ResponsiveContext.Provider>
  )
...

If you use next.js, structure your import like this to disable server-side rendering for components that use this library:

import dynamic from 'next/dynamic'
const MediaQuery = dynamic(() => import('react-responsive'), {
  ssr: false
})
Testing
import { Context as ResponsiveContext } from 'react-responsive'
import { render } from '@testing-library/react'
import ProductsListing from './ProductsListing'

describe('ProductsListing', () => {
  test('matches the snapshot', () => {
    const { container: mobile } = render(
      <ResponsiveContext.Provider value={{ width: 300 }}>
        <ProductsListing />
      </ResponsiveContext.Provider>
    )
    expect(mobile).toMatchSnapshot()

    const { container: desktop } = render(
      <ResponsiveContext.Provider value={{ width: 1000 }}>
        <ProductsListing />
      </ResponsiveContext.Provider>
    )
    expect(desktop).toMatchSnapshot()
  })
})

Note that if anything has a device prop passed in it will take precedence over the one from context.

onChange

You can use the onChange callback to specify a change handler that will be called when the media query's value changes.

import React from 'react'
import { useMediaQuery } from 'react-responsive'

const Example = () => {
  const handleMediaQueryChange = (matches) => {
    // matches will be true or false based on the value for the media query
  }
  const isDesktopOrLaptop = useMediaQuery(
    { minWidth: 1224 },
    undefined,
    handleMediaQueryChange
  )

  return <div>...</div>
}
import React from 'react'
import MediaQuery from 'react-responsive'

const Example = () => {
  const handleMediaQueryChange = (matches) => {
    // matches will be true or false based on the value for the media query
  }

  return (
    <MediaQuery minWidth={1224} onChange={handleMediaQueryChange}>
      ...
    </MediaQuery>
  )
}

Easy Mode

That's it! Now you can create your application specific breakpoints and reuse them easily. Here is an example:

import { useMediaQuery } from 'react-responsive'

const Desktop = ({ children }) => {
  const isDesktop = useMediaQuery({ minWidth: 992 })
  return isDesktop ? children : null
}
const Tablet = ({ children }) => {
  const isTablet = useMediaQuery({ minWidth: 768, maxWidth: 991 })
  return isTablet ? children : null
}
const Mobile = ({ children }) => {
  const isMobile = useMediaQuery({ maxWidth: 767 })
  return isMobile ? children : null
}
const Default = ({ children }) => {
  const isNotMobile = useMediaQuery({ minWidth: 768 })
  return isNotMobile ? children : null
}

const Example = () => (
  <div>
    <Desktop>Desktop or laptop</Desktop>
    <Tablet>Tablet</Tablet>
    <Mobile>Mobile</Mobile>
    <Default>Not mobile (desktop or laptop or tablet)</Default>
  </div>
)

export default Example

And if you want a combo (the DRY way):

import { useMediaQuery } from 'react-responsive'

const useDesktopMediaQuery = () =>
  useMediaQuery({ query: '(min-width: 1280px)' })

const useTabletAndBelowMediaQuery = () =>
  useMediaQuery({ query: '(max-width: 1279px)' })

const Desktop = ({ children }) => {
  const isDesktop = useDesktopMediaQuery()

  return isDesktop ? children : null
}

const TabletAndBelow = ({ children }) => {
  const isTabletAndBelow = useTabletAndBelowMediaQuery()

  return isTabletAndBelow ? children : null
}

Browser Support

Out of the box

Chrome9
Firefox (Gecko)6
MS EdgeAll
Internet Explorer10
Opera12.1
Safari5.1

With Polyfills

Pretty much everything. Check out these polyfills: