• Stars
    star
    6,999
  • Rank 5,545 (Top 0.2 %)
  • Language
    TypeScript
  • License
    MIT License
  • Created about 10 years ago
  • Updated 6 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

CSS media queries in react - for responsive design, and more.

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/contra/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:

More Repositories

1

windows_98.css

some sick styles for your guestbook
CSS
797
star
2

rtc-everywhere

Cross-everything WebRTC mega-project
JavaScript
651
star
3

holla

An abstraction over P2P video/voice/data connections using WebRTC
JavaScript
645
star
4

smog

HTML5/Node/WebSocket MongoDB panel
JavaScript
443
star
5

JMD

Java bytecode analysis/deobfuscation tool
Java
199
star
6

captchagen

Captcha generation for NodeJS
JavaScript
179
star
7

nodecast

Node interface to DIAL/RAMP/ChromeCast
JavaScript
160
star
8

blink-polyfill

Fix idiocy in newer browsers
CSS
152
star
9

bank

simple.com API client
JavaScript
123
star
10

immutable-props

React PropTypes for Immutable.js
JavaScript
96
star
11

wifi-location

Triangulate your WiFi signal to guess geolocation
JavaScript
92
star
12

are-you-a-cop

Blocks cops from visiting your site. If they are they have to tell you.
JavaScript
79
star
13

node-linq

LINQ for node
CoffeeScript
78
star
14

node-gdal-next

Node.js bindings for GDAL (Geospatial Data Abstraction Library) [Fork]
C++
75
star
15

camera

Create readable streams from connected webcams
JavaScript
69
star
16

spotcrime

API client for crime statistics
JavaScript
65
star
17

xmlson

XML/JSON conversion
CoffeeScript
57
star
18

CJBE

Continued Java Bytecode Editor, a tool for modifying and analyzing java bytecode structures and class files
Java
41
star
19

deprecated

Tool for deprecating things
JavaScript
37
star
20

gasp

A declarative layer on top of gulp
JavaScript
37
star
21

sutro

Declarative slightly-opinionated API framework
TypeScript
32
star
22

pinger

Native ICMP ping for node
JavaScript
30
star
23

4chanjs

NodeJS and Browser 4chan API client
JavaScript
30
star
24

TinyShell

A very tiny PHP shell
PHP
27
star
25

glob2base

Extracts a base path from a node-glob instance
JavaScript
26
star
26

dope.travel

Aggregating the coolest shit on earth
25
star
27

jif

Dead simple ternary or if/else replacement
JavaScript
22
star
28

rover

A node.js client for controlling BrookStone Rover 2.0s
JavaScript
22
star
29

net-sim

Simulate network conditions
JavaScript
21
star
30

hymn

React audio player component
JavaScript
20
star
31

faces

Facial recognition
CoffeeScript
19
star
32

JMOT

Java multi-purpose obfuscation utility, a tool for manipulating and obfuscating java bytecode structures. Generates the algorithm that generates the algorithm that will manipulate the code so it is nearly impossible to reverse engineer
Java
19
star
33

try-parse

Try to parse different data types from strings and objects of strings
JavaScript
18
star
34

react-logger

Dead simple logging mixin for react
JavaScript
17
star
35

gifbooth

gif booth for a projector
JavaScript
15
star
36

generate-calendar-url

generate a url to add an event to your calendar
JavaScript
15
star
37

papajohns

Client for the unofficial Papa Johns API
JavaScript
15
star
38

hd.css

Bringing HD Vision Goggles to the web
HTML
14
star
39

PEIK

Properly Engineered Infection Kit, A framework for creating malware in C#. Multi-threaded, comes with a built-in MSIL obfuscator and packer to prevent detection
C#
14
star
40

data-phx

A list of data for scraping/crawling/etc.
13
star
41

thinky-export-schema

Export a schema to a normal object for serialization
JavaScript
12
star
42

native-keyboard

Higher level keyboard binding for node apps
JavaScript
11
star
43

cidr

CIDR IP operations for node
CoffeeScript
10
star
44

djb2

djb2 hash in js
CoffeeScript
9
star
45

drone

Code for messing with an AR drone
JavaScript
9
star
46

instax

API client for controlling the Instax Share SP-1 Polaroid printer
JavaScript
9
star
47

rethinkdb-boundaries

Import US Census TIGER data into RethinkDB as GeoJSON
JavaScript
8
star
48

nextback

Wraps callbacks in async
JavaScript
8
star
49

JBird

Tool for creating undetectable java malware. Comes with a built-in custom obfuscator that uses randomly generated crypto algorithms to prevent detection forever
Java
7
star
50

handle-async

Resolves any function to a value. Generators, callbacks, promises, flat values - don't worry about it!
JavaScript
7
star
51

pretty-metric

Parse, convert, and humanize metric sizes
JavaScript
7
star
52

DotCrack

General .NET/MSIL assembly manipulation/reverse engineering utility
C#
7
star
53

BetterError

A better Error class
JavaScript
7
star
54

vinyl-fs-tree

Create a filesystem tree from vinyl files
JavaScript
7
star
55

msr

JavaScript
6
star
56

soundcloud-lookup

Simply look up info about a URL on soundcloud
JavaScript
6
star
57

sequelize-where

Pure JS implementation of the sequelize query language (where)
JavaScript
6
star
58

rethinkdb-change-stream

Transform rethinkdb change feeds into node streams
JavaScript
5
star
59

BetterRegExp

Utility wrapper over RegExp
CoffeeScript
5
star
60

fotio

Photos
JavaScript
5
star
61

nova

Run NodeJS code in the browser!
JavaScript
5
star
62

revisit

Wrapper around revisit.link spec
JavaScript
5
star
63

node-shodan

Shodan API for node
CoffeeScript
5
star
64

react-swipeable

Swipe right and swipe left with animations
JavaScript
5
star
65

snapchat-blacklist

this is a list of ppl who are evil and screenshot snaps
4
star
66

fixnode

Fixes a bunch of shitty problems
JavaScript
4
star
67

react-flex-lite

Flexbox components for React, as minimal as possible
TypeScript
4
star
68

lobbying

automated lobbying
JavaScript
4
star
69

LOLShell

Remote PHP shell that utilizes new technologies and modern practices
PHP
4
star
70

puzzle-box

Sandboxing with call tracing and more
JavaScript
3
star
71

npm-boilerplate-node

JavaScript
3
star
72

PiFM

Raspberry Pi FM Transmission using NodeJS
C
3
star
73

sleep-schedule

Optimize your sleep
JavaScript
3
star
74

JHook

Overrides standard JVM classes for reverse engineering and debugging purposes
Java
3
star
75

app-config-chain

Cascading configuration for web applications
JavaScript
3
star
76

CooLogger

EXTREMELY OLD - .NET keylogger/malware builder. Steals passwords for most common protocols. Mainly built to test a .NET auth system I was working on
C#
3
star
77

minebot

CoffeeScript
3
star
78

surfer

Surfboard modem restarter
JavaScript
2
star
79

hackery

Hacking utilities for node
CoffeeScript
2
star
80

react-npm-boilerplate

npm module boilerplate
JavaScript
2
star
81

camr

Public facing webcam finder
CoffeeScript
2
star
82

DotNOS

.NET Opcode Sanitizer, a tool that deobfuscates MSIL bytecode by removing invalid opcodes using Mono.cecil
C#
2
star
83

MacFinder

EXTREMELY OLD - Crawls and analyzes craigslist listings to find Macbooks with high resale profit margins
Python
2
star
84

aa-rewards

experiments with the american airlines api
CoffeeScript
2
star
85

boiler

Application boilerplate
JavaScript
2
star
86

npm-geo

Statistics about npm modules by geolocation
JavaScript
2
star
87

gulp-log-emitter

Emit log message objects on node's process object
JavaScript
2
star
88

dev-env

VMWare Developer Image
1
star
89

rethink-decl

Declarative RethinkDB queries
JavaScript
1
star
90

midi

MIDI playground for the raspberry pi
CoffeeScript
1
star
91

az-pollutes

Arizona Pollution site for CodeForPHX
JavaScript
1
star
92

good-stuff

Curated events/places by city
JavaScript
1
star
93

lsd

some webrtc + css filter experiments
JavaScript
1
star
94

embedly-lookup

Simply look up info about a URL on embed.ly
JavaScript
1
star
95

noscope

hitmarkers for the web
JavaScript
1
star
96

framework

MVC framework for NodeJS
JavaScript
1
star
97

syrup

A whitespace-significant Lisp, in CoffeeScript, for funsies.
CoffeeScript
1
star
98

sutro-client

A simple and sugary client for using sutro APIs.
JavaScript
1
star
99

yocontra.github.io

my site
JavaScript
1
star
100

nelson

NodeJS mocking library
CoffeeScript
1
star