Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

react-responsive

yocontra3.2mMIT10.0.0TypeScript support: included

Media queries in react for responsive design

css, react-component, viewport, react, mobile, media queries, respond, media query, matchMedia, responsive, component

readme

react-responsive NPM version Downloads

Information

Packagereact-responsive
Description Media 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

Chrome 9
Firefox (Gecko) 6
MS Edge All
Internet Explorer 10
Opera 12.1
Safari 5.1

With Polyfills

Pretty much everything. Check out these polyfills:

changelog

Change Log

v10.0.0

  • Package with rollup
  • Adds ESM support
  • Removes UMD support - CJS support still exists
    • Still need UMD support? Stick with v9.0.1
  • Upgraded all dependencies to latest
  • Bumps minimum node version to 14 (dependencies are all at 14 anyways)

v9.0.1

  • Export MediaQueryMatchers type

v9.0.0

  • Convert project to typescript
  • Upgrade to Webpack 5
  • Fix a memory leak with useMediaQuery hook
  • Add support for React 18
  • Add docs webpage

v9.0.0-beta

Beta 9

  • Fix typescript output

Beta 8

  • Fix webpack bundle issue (self is not defined)

Beta 7

  • Improve typescript typings
  • Add typing support for React 18
  • Example setup with React 18
  • Upgrade to Webpack 5
  • Fix a bug with React 18 not re-rendering

Beta 6

  • Convert project to typescript
  • Remove UMD build from project
  • Remove samples from project
  • Add docs webpage
  • Fix a memory leak with useMediaQuery hook

v8.2.0

  • Repo maintenance - update dev dependencies and linter. Source maps updated.

v8.1.0

  • Expose toQuery function for turning our MediaQuery objects into strings

v8.0.3

  • Republish of 8.0.1 - version 8.0.2 was causing issues for people and is deprecated.

v8.0.1

  • Include src folder in package for webpack to get proper sourcemaps

v8.0.0

  • Adds Hooks API to make everything way easier (Thanks to @Tomekmularczyk)
    • See README for more info on how to use it
  • [BREAKING] Change values prop to device

v7.0.0

  • Adds Context support to make testing and server-side rendering much easier (Thanks to @Tomekmularczyk)
    • See README for more info on how to use it
  • [BREAKING] Require React v16.8.0 or higher

v6.1.2

v6.1.1

  • Fix forceStatic issue with previous release

v6.1.0

  • Fix values prop existence not forcing static query resolution (Thanks @Herdismaria)

v6.0.0

  • Require React v16.3.0 or higher
  • Update and simplify all lifecycle functions
  • Remove all support for wrapper elements
    • Previously, when either component or non-mediaquery props were provided, we would render a wrapper element. This behavior no longer exists.
    • The rendering logic is now a basic ternary - matches ? props.children : null
  • Thanks to @whatknight for doing the work here.

v5.0.0

v4.0.5 (2018/03/07 17:11 +00:00)

  • e61ec94 4.0.5 (@contra)
  • a8ec8e6 pre-release (@contra)
  • #146 Guard against null children (@lunaleaps)
  • 3b40652 Guard against null children (@lunaleaps)

v4.0.4 (2018/02/09 22:43 +00:00)

v4.0.3 (2017/11/22 03:26 +00:00)

v4.0.2 (2017/11/21 19:55 +00:00)

v4.0.1 (2017/11/21 15:54 +00:00)

v4.0.0 (2017/11/16 00:14 +00:00)

  • b78938d 4.0.0 (@contra)
  • bd1c554 deps (@contra)
  • #132 fix: support React 16 fragments (@jessepinho)
  • aefef55 chore: build assets (@jessepinho)
  • 184b88e style: make wrapChildren one line (@jessepinho)
  • 95edc69 feat: don't wrap strings, either (@jessepinho)
  • 0436fb5 chore: update React peer dependency (@jessepinho)
  • 36f8372 fix: support React 16 fragments (@jessepinho)
  • #130 docs(CHANGELOG): 3.0.0 (@evenchange4)
  • aaceb45 docs(CHANGELOG): 3.0.0 (@evenchange4)
  • #129 Fix view duplication in common uses example (@sonaye)
  • 55a0f47 Fix view duplication in common uses example (@sonaye)
  • edbd8e7 3.0 (@contra)

v3.0.0 (2017/10/18 00:14 +00:00)

  • 8a318fe 3.0.0 (@contra)
  • 6bf6814 deps (@contra)
  • #128 Fix linter and tests (@refinery29)
  • 71b611e Fix repo attribution (@cribbles)
  • 4e8186a Fix test (import as default) (@cribbles)
  • ce0475b Lint (remove semicolon) (@cribbles)
  • 73e2862 Add toQuery to default exports (@cribbles)
  • #124 Export toQuery function directly since src folder is no longer exported (@morganmccrory)
  • f5d9b8b Export toQuery function directly since src folder is no longer exported (@morganmccrory)
  • fb23be4 log (@contra)

v2.0.0 (2017/10/02 21:11 +00:00)

  • dee5570 2.0.0 (@contra)
  • 24ff262 stupid lock file (@contra)
  • cb120f8 house clean (@contra)
  • 1e05b0c housekeeping (@contra)
  • 14004ab housekeeping (@contra)
  • 8ff7425 rebuild (@contra)
  • #120 support react 16. (@whatknight)
  • 6b300d7 Merge branch 'master' into react16 (@contra)
  • #119 Housekeeping (@whatknight)
  • #121 Update README.txt (@vpicone)
  • 1d19af9 Update README.txt (@vpicone)
  • bb69da2 support react 16. (@whatknight)
  • e78cab9 bump sinon (@whatknight)
  • 8380bd9 update webpack (@whatknight)
  • 9429386 remove transform runtime (@whatknight)
  • 48b2a33 update test deps (@whatknight)
  • 81d9d18 update eslint (@whatknight)
  • 307b31d update babel config (@whatknight)
  • #117 Update README.md (@modosc)
  • 0b4d019 Update README.md (@modosc)
  • c55a77e closes #116 (@contra)

v1.3.4 (2017/07/14 21:36 +00:00)

  • c93ac7a 1.3.4 (@contra)
  • #109 fix Cannot read property 'removeListener' of undefined (@modosc)
  • ea3d577 update matchmediaquery@^0.2.1
  • 3687115 fix Cannot read property 'removeListener' of undefined
  • 83c2409 1.3.3 (@contra)

v1.3.3 (2017/07/14 19:32 +00:00)

  • 58fdb89 1.3.3 (@contra)
  • e3781d2 diff (@contra)
  • #108 fix PropTypes warnings, fix react-addons-test-utils deprecation, fix … (@modosc)
  • 49919d0 fix PropTypes warnings, fix react-addons-test-utils deprecation, fix eslint to work with test/
  • 9957f24 1.3.2 (@contra)

v1.3.2 (2017/07/14 14:47 +00:00)

  • a595593 1.3.2 (@contra)
  • 516f270 merge (@contra)
  • 40fe34e build (@contra)
  • 85ae4cd build (@contra)
  • 69cde10 changes (@contra)
  • #106 Fixing a memory leak. (@ncochard)
  • 00af280 1.3.1
  • 1e8dcb9 Created 'matchmediaquery' as a replacement for 'matchmedia'.
  • 6df7684 Fix for a memory leak.
  • #102 Close #74 (@WRONGWAY4YOU)
  • 7877b80 Merge branch 'master' into iss74 (@wrongway4you)
  • 374b290 Close #74 (@wrongway4you)
  • 4156475 Merge branch 'remove-npm-bin-prefixes' (@wrongway4you)
  • #101 Remove unneeded "$(npm bin)/" prefixes (@WRONGWAY4YOU)
  • adfaf69 Remove unneeded "$(npm bin)/" prefixes in package.json (@wrongway4you)
  • #100 Document common use cases (@sonaye)
  • b917322 Document common use cases (@sonaye)

v1.3.0 (2017/05/09 01:13 +00:00)

  • 44a7bf8 1.3.0 (@contra)
  • #97 Add onChange and onChangeBefore callbacks (@hiddenboox)
  • 6cb52b1 Add onBeforeChange callback (@hiddenboox)
  • #96 Adding demo link to readme (@scottwarren)
  • 5836dfe Adding link to readme (@scottwarren)
  • 2c6b00d Add onChange callback (@d4rky-pl)

v1.2.10 (2017/04/19 18:32 +00:00)

v1.2.9 (2017/04/19 03:27 +00:00)

  • 07849af 1.2.9 (@contra)
  • #90 Replace proptypes in index file (@rmdort)
  • a4a9120 Removed React proptype in index (@rmdort)
  • c1a8081 Spellfix (@rmdort)
  • 0d7ffb6 Replace react proptypes (@rmdort)
  • 48c303f build (@contra)

v1.2.8 (2017/04/18 18:45 +00:00)

  • 4778c1e 1.2.8 (@contra)
  • #88 Added prop-type library for React 16 (@rmdort)
  • 7039ef6 Added prop-type library for react 16 (@rmdort)
  • #86 docs(readme): add install part (@kud)
  • 4665934 docs(readme): add install part (@kud)
  • 8c53639 changelog (@contra)

v1.2.7 (2017/03/14 16:17 +00:00)

  • ee6b142 1.2.7 (@contra)
  • #83 Add react 0.14.x as potential peer dep (@jesstelford)
  • 29266f0 Peer dep on all react versions (@jesstelford)
  • 1007031 Add react 0.14.x as potential peer dep (@jesstelford)
  • bc69299 changes (@contra)

v1.2.6 (2017/01/19 03:06 +00:00)

v1.2.4 (2016/11/24 00:51 +00:00)

v1.2.3 (2016/11/23 00:26 +00:00)

v1.2.2 (2016/11/22 23:57 +00:00)

  • d337ce3 1.2.2 (@contra)
  • #70 Wrap children if it's single-element array (@Instamotor-Labs)
  • 341fdec Wrap children if it's single-element array (@skydan)
  • #65 Use ES2015 (@whatknight)
  • 1b07af3 Clean up webpack file syntax. (@whatknight)
  • b72e2c0 Update source to ES2015 syntax. (@whatknight)
  • 94dbf57 add gitbook stuff. (@whatknight)
  • 6aa759d autofix lint errors (@whatknight)
  • 902d432 Use eslint instead of jshint. (@whatknight)
  • 9b22166 Remove gulp. (@whatknight)
  • 2810466 Build using babel and webpack. (@whatknight)
  • 43b5741 update author, license, and urls. (@whatknight)
  • 477174c 1.2.1 (@contra)
  • f185c21 rebuild (@contra)
  • 7895cde 1.2.0 (@contra)
  • #64 Pass function as children. (@whatknight)
  • 5ce699b Add space to readme. (@whatknight)
  • b27da86 Update docs with new feature. (@whatknight)
  • 80fddd9 Add ability to render with a function as the component child. (@whatknight)

v1.1.5 (2016/09/15 04:13 +00:00)

  • b6364b6 1.1.5 (@contra)
  • #62 Fix for Uncaught Invariant Violation #56. (@rhavill)
  • 3199bef Added unit test to make sure MediaQuery render function can handle an empty array as children.
  • fdb34e8 Fix for Uncaught Invariant Violation #56. Return null from render function when MediaQuery has no children.
  • #61 Small fixes to indentation in README (@TSMMark)
  • b75d5d8 small fixes to indentation in README (@TSMMark)
  • eac6444 1.1.4 (@contra)
  • #58 Doesn't throw error with empty children (@nkov)
  • df33365 doesnt throw error with empty children (@nkov)

v1.1.3 (2016/04/25 17:03 +00:00)

  • ba1cb39 1.1.3 (@contra)
  • #53 Always wrap children if it's a string. (@whatknight)
  • 23f35cb Always wrap children if it's a string. (@whatknight)
  • 02dd120 add dev dep for react (@contra)
  • #52 Add testing with jsdom. (@whatknight)
  • #51 Fix bug where string would cause invariant error. (@whatknight)
  • 55707f1 Add testing with jsdom. (@whatknight)
  • 7dacb42 Fix bug where string would cause invariant error. (@whatknight)

v1.1.2 (2016/04/08 05:07 +00:00)

  • 8d03ff0 1.1.2 (@contra)
  • #47 Bump react peer dependency to allow v15 (@cesarandreu)
  • 87619fe Bump react peer dependency to allow v15 (@cesarandreu)
  • #46 Use API to examine number of children (@jdlehman)
  • 6c75c26 Use API to examine number of children (@jdlehman)
  • c82c671 1.1.1 (@contra)
  • #39 fixed usage of Object.assign for older browsers (@pekeler)
  • ce639c9 fixed usage of Object.assign for older browsers (@pekeler)

v1.1.0 (2016/01/10 23:53 +00:00)

  • cfff39a 1.1.0 (@contra)
  • #37 Without lodash (@pekeler)
  • ea47d21 reverted spelling, dist (@pekeler)
  • 26e540d reverted spelling (@pekeler)
  • 1cd1947 readded old react versions (@pekeler)
  • #38 reverted stupid spelling (@pekeler)
  • 996f15e reverted stupid spelling (@pekeler)
  • #36 Newer dependencies (@pekeler)
  • 83f461b replaced lodash.omit with own implementation to reduce total file size (@pekeler)
  • 4534c1f make npm test work (@pekeler)
  • 5cd9036 updated to latest dependecies, sample can't be easily backwards compatible with old react versions so we focus on the latest react (@pekeler)
  • 29d0d08 more readme info (@contra)

v1.0.1 (2015/11/13 20:28 +00:00)

  • b4ce24e 1.0.1 (@contra)
  • #32 Add children to excluded keys (@ch2ch3)
  • 30b3f9f Add children to excluded keys (@ch2ch3)

v1.0.0 (2015/11/09 23:48 +00:00)

  • a20d7f3 1.0.0 (@contra)
  • #30 Do not require a component to wrap MediaQuery children (@jdlehman)
  • 27c09e5 Pass props to single child even if not using a wrapper (@jdlehman)
  • 56ecbb2 Add documentation for component prop (@jdlehman)
  • 4543f17 Do not require a component to wrap MediaQuery children (@jdlehman)

v0.0.10 (2015/10/08 22:50 +00:00)

  • 62af1d5 0.0.10 (@contra)
  • #28 support react 0.14 (@0x80)
  • d1dc1e9 support react 0.14 (@0x80)
  • #26 Allow for react 0.14.0-rc1 as peer-dependency (@npasserini)
  • b3e687d Allow for react 0.14.0-rc1 as peer-dependency (@npasserini)

v0.0.8 (2015/08/13 20:18 +00:00)

  • 969736a 0.0.8 (@contra)
  • #18 There is possible memory leak and bug leads to many listeners. It is … (@vavdav)
  • d435265 There is possible memory leak and bug leads to many listeners. It is necessary to remove listener before creating new object. (@vavdav)
  • #17 Add support for React 0.14.0-beta1 (@frederickfogerty)
  • 45861f7 Update package.json (@frederickfogerty)
  • 84fb5a8 Add support for React 0.14.0-beta1 (@frederickfogerty)
  • #16 Use hyphenate-style-name module instead of React internal (@rexxars)
  • 7046106 Use hyphenate-style-name module instead of React internal (@rexxars)

v0.0.7 (2015/07/22 06:22 +00:00)

v0.0.6 (2015/03/30 17:12 +00:00)

  • e9214ce 0.0.6 (@contra)
  • 7bcb9b5 fix linting (@contra)
  • #12 Provide more flexible React peer dependency range (@colindresj)
  • 7db99e3 Provide more flexible React peer dependency range (@colindresj)
  • #11 switch to matchmedia module for client/server abstraction (@phated)
  • 7d05ab6 change names to MediaQuery and add all type (@phated)
  • 39ab71d add type property (@phated)
  • 6c6054a update readme (@phated)
  • 48e6c5d update reactify, add example, use React.PropTypes.shape to define values (@phated)
  • 759154b switch to matchmedia module for client/server abstraction (@phated)

v0.0.5 (2015/02/17 23:42 +00:00)

  • 72f4e25 0.0.5 (@contra)
  • acef7f0 lint fixes (@contra)
  • #10 fix usage of idiomatic react props (@ChrisSki)
  • 27e9f25 remove propTypes: types (@ChrisSki)
  • 6f4b364 actually remove types this time (@ChrisSki)
  • dcdea6a remove types prop (@ChrisSki)
  • 207a385 fix usage of idiomatic react props (@ChrisSki)

v0.0.4 (2015/02/09 09:15 +00:00)

  • 4f91d06 0.0.4 (@contra)
  • 609e3ae fix linter (@contra)
  • #9 mergeInto removed and window checked (@fvitullo)
  • c9eef42 fixes #7
  • 26f2e95 mergeInto replaced with object-assign

v0.0.3 (2015/02/04 01:12 +00:00)

v0.0.2 (2015/01/27 20:11 +00:00)