├── .gitignore
├── .npmignore
├── LICENSE
├── README.md
├── bower.json
├── gulpfile.js
├── package.json
├── react_media_queryable.js
├── react_media_queryable.min.js
├── src
├── media_listener.js
└── media_queryable.js
└── webpack.config.js
/.gitignore:
--------------------------------------------------------------------------------
1 | /node_modules/
2 |
--------------------------------------------------------------------------------
/.npmignore:
--------------------------------------------------------------------------------
1 | gulpfile.js
2 | webpack.config.js
3 | src
4 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Copyright (c) 2015 Substantial
2 |
3 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
4 |
5 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
6 |
7 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
8 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | react-media-queryable
2 | =====================
3 |
4 | Trigger state updates when a media query matches the current state of the browser.
5 |
6 | Background
7 | ----------
8 |
9 | [Adaptive Design](https://developer.mozilla.org/en-US/Apps/Design/UI_layout_basics/Responsive_design_versus_adaptive_design)
10 | is characterized as rendering only the content that a user's browser is equipped to handle. This is often used in scenarios where you want the markup for a component to differ based on screen size: showing a table of data, for example, on a desktop-class screen while showing the data as a list on a mobile-class screen.
11 |
12 | Typically, Adaptive Design is a server-side methodology, where the server parses the User Agent string and delivers the best experience based on the data found there. Server-side User Agent sniffing, however, can be complex, hard to maintain, and often wrong. Single page apps written in JavaScript generate the HTML on the client side and can't take advantage of any server-side Adaptive Design implementation.
13 |
14 | react-media-queryable is a React component that allows child components to know the rendering capabilities of the browser (via [media queries](https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Media_queries)) and decide how to render themselves based on those capabilities.
15 |
16 | Usage
17 | -----
18 |
19 | Use it like any other React component, passing it a set of named media queries as `props`:
20 |
21 | ```js
22 | var MediaQueryable = require('react-media-queryable'); // also available via amd define or window global
23 | var mediaQueries = {
24 | small: "(max-width: 800px)",
25 | large: "(min-width: 801px)"
26 | };
27 |
28 |
Desktop Experience!
; 45 | } else { 46 | returnMobile Experience!
; 47 | } 48 | } 49 | }); 50 | ``` 51 | 52 | Whenever a new media query is matched (i.e. screen rotation or browser window resize), the `mediaQuery` prop will update, forcing a re-render of the child component. The media query object that you pass into the `MediaQueryable` component can contain any browser-supported media query definitions. 53 | 54 | Compatibility 55 | ------------- 56 | 57 | This library makes use of the [`window.matchMedia`](https://developer.mozilla.org/en-US/docs/Web/API/Window/matchMedia) API that's available in IE 10+. If you want to use it in older browsers, you can use the [matchMedia polyfill](https://github.com/paulirish/matchMedia.js/). 58 | 59 | License 60 | ------- 61 | Copyright (c) 2015 Substantial 62 | 63 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 64 | 65 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 66 | 67 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 68 | -------------------------------------------------------------------------------- /bower.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "react-media-queryable", 3 | "main": "react_media_queryable.js", 4 | "version": "1.0.6", 5 | "homepage": "https://github.com/substantial/react-media-queryable", 6 | "authors": [ 7 | "Substantial" 8 | ], 9 | "description": "Trigger state update on media query change.", 10 | "moduleType": [ 11 | "amd", 12 | "globals", 13 | "node" 14 | ], 15 | "keywords": [ 16 | "react", 17 | "media", 18 | "query", 19 | "adaptive", 20 | "responsive" 21 | ], 22 | "license": "MIT", 23 | "ignore": [ 24 | "**/.*", 25 | "node_modules", 26 | "gulpfile.js", 27 | "webpack.config.js", 28 | "src" 29 | ] 30 | } 31 | -------------------------------------------------------------------------------- /gulpfile.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | var gulp = require('gulp'); 4 | var webpack = require('webpack-stream'); 5 | var uglify = require('gulp-uglify'); 6 | var sourcemaps = require('gulp-sourcemaps'); 7 | var rename = require('gulp-rename'); 8 | var path = require('path'); 9 | 10 | var basename = 'react_media_queryable'; 11 | 12 | gulp.task('bundle', function() { 13 | return gulp.src(path.join('./src/media_queryable.js')) 14 | .pipe(webpack(require('./webpack.config.js'))) 15 | .pipe(gulp.dest('./')); 16 | }); 17 | 18 | gulp.task('compress', ['bundle'], function() { 19 | return gulp.src(path.join('./' + basename + '.js')) 20 | .pipe(uglify()) 21 | .pipe(sourcemaps.init({loadMaps: true})) 22 | .pipe(sourcemaps.write('./')) 23 | .pipe(rename(basename + '.min.js')) 24 | .pipe(gulp.dest('./')); 25 | }); 26 | 27 | gulp.task('default', ['compress']); 28 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "react-media-queryable", 3 | "version": "2.1.0", 4 | "description": "Trigger state update on media query change.", 5 | "main": "react_media_queryable.js", 6 | "scripts": { 7 | "test": "null" 8 | }, 9 | "repository": { 10 | "type": "git", 11 | "url": "https://github.com/substantial/react-media-queryable.git" 12 | }, 13 | "keywords": [ 14 | "react", 15 | "media", 16 | "query", 17 | "adaptive", 18 | "responsive" 19 | ], 20 | "author": "Substantial", 21 | "license": "MIT", 22 | "bugs": { 23 | "url": "https://github.com/substantial/react-media-queryable/issues" 24 | }, 25 | "homepage": "https://github.com/substantial/react-media-queryable", 26 | "peerDependencies": { 27 | "react": "*" 28 | }, 29 | "devDependencies": { 30 | "gulp": "^3.9.0", 31 | "gulp-rename": "^1.2.2", 32 | "gulp-sourcemaps": "^1.5.2", 33 | "gulp-uglify": "^1.2.0", 34 | "object-assign": "^4.1.0", 35 | "webpack": "^1.9.10", 36 | "webpack-stream": "^2.0.0" 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /react_media_queryable.js: -------------------------------------------------------------------------------- 1 | (function webpackUniversalModuleDefinition(root, factory) { 2 | if(typeof exports === 'object' && typeof module === 'object') 3 | module.exports = factory(require("react")); 4 | else if(typeof define === 'function' && define.amd) 5 | define(["react"], factory); 6 | else if(typeof exports === 'object') 7 | exports["MediaQueryable"] = factory(require("react")); 8 | else 9 | root["MediaQueryable"] = factory(root["React"]); 10 | })(this, function(__WEBPACK_EXTERNAL_MODULE_1__) { 11 | return /******/ (function(modules) { // webpackBootstrap 12 | /******/ // The module cache 13 | /******/ var installedModules = {}; 14 | 15 | /******/ // The require function 16 | /******/ function __webpack_require__(moduleId) { 17 | 18 | /******/ // Check if module is in cache 19 | /******/ if(installedModules[moduleId]) 20 | /******/ return installedModules[moduleId].exports; 21 | 22 | /******/ // Create a new module (and put it into the cache) 23 | /******/ var module = installedModules[moduleId] = { 24 | /******/ exports: {}, 25 | /******/ id: moduleId, 26 | /******/ loaded: false 27 | /******/ }; 28 | 29 | /******/ // Execute the module function 30 | /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); 31 | 32 | /******/ // Flag the module as loaded 33 | /******/ module.loaded = true; 34 | 35 | /******/ // Return the exports of the module 36 | /******/ return module.exports; 37 | /******/ } 38 | 39 | 40 | /******/ // expose the modules object (__webpack_modules__) 41 | /******/ __webpack_require__.m = modules; 42 | 43 | /******/ // expose the module cache 44 | /******/ __webpack_require__.c = installedModules; 45 | 46 | /******/ // __webpack_public_path__ 47 | /******/ __webpack_require__.p = ""; 48 | 49 | /******/ // Load entry module and return exports 50 | /******/ return __webpack_require__(0); 51 | /******/ }) 52 | /************************************************************************/ 53 | /******/ ([ 54 | /* 0 */ 55 | /***/ function(module, exports, __webpack_require__) { 56 | 57 | var React = __webpack_require__(1); 58 | var MediaListener = __webpack_require__(2); 59 | var assign = __webpack_require__(3); 60 | 61 | module.exports = React.createClass({ 62 | displayName: 'MediaQueryable', 63 | mediaListener: null, 64 | propTypes: { 65 | className: React.PropTypes.string, 66 | defaultMediaQuery: React.PropTypes.string.isRequired, 67 | mediaQueries: React.PropTypes.object.isRequired, 68 | style: React.PropTypes.object, 69 | }, 70 | 71 | getInitialState: function() { 72 | return { 73 | mediaQuery: undefined 74 | }; 75 | }, 76 | 77 | componentDidMount: function() { 78 | this.mediaListener = new MediaListener(this.props.mediaQueries, this._onMediaQueryChange); 79 | }, 80 | 81 | componentWillUnmount: function() { 82 | if (this.mediaListener) { 83 | this.mediaListener.stopListening(); 84 | } 85 | }, 86 | 87 | render: function() { 88 | var mediaQuery = this._currentMediaQuery(); 89 | if (!mediaQuery) { 90 | return null; 91 | } 92 | 93 | var renderedChildren = React.Children.map(this.props.children, function(child) { 94 | if (child !== null) { 95 | return React.cloneElement(child, { mediaQuery: this._currentMediaQuery() } ); 96 | } 97 | }, this); 98 | return React.DOM.div(assign({}, {children: renderedChildren, className: this.props.className, style: this.props.style})); 99 | }, 100 | 101 | _currentMediaQuery: function() { 102 | return this.state.mediaQuery || this.props.defaultMediaQuery || null; 103 | }, 104 | 105 | _onMediaQueryChange: function(name) { 106 | this.setState({ 107 | mediaQuery: name 108 | }); 109 | } 110 | }); 111 | 112 | 113 | /***/ }, 114 | /* 1 */ 115 | /***/ function(module, exports) { 116 | 117 | module.exports = __WEBPACK_EXTERNAL_MODULE_1__; 118 | 119 | /***/ }, 120 | /* 2 */ 121 | /***/ function(module, exports) { 122 | 123 | function MediaListener(mediaQueries, changeHandler) { 124 | this.changeHandler = changeHandler; 125 | this.mqls = this._buildMediaQueryLists(mediaQueries); 126 | } 127 | 128 | MediaListener.prototype.stopListening = function() { 129 | var name; 130 | for (name in this.mqls) { 131 | var mql = this.mqls[name]; 132 | mql.removeListener && 133 | mql.removeListener(mql._fn); 134 | } 135 | }; 136 | 137 | MediaListener.prototype._buildMediaQueryLists = function(mediaQueries) { 138 | if (!window.matchMedia) return {}; 139 | 140 | var mqls = {}; 141 | var name; 142 | for (name in mediaQueries) { 143 | var mql = this._setupListeners(name, mediaQueries[name]); 144 | mqls[name] = mql; 145 | 146 | this._handleMediaQueryChange(mql.matches, name); 147 | } 148 | return mqls; 149 | }; 150 | 151 | MediaListener.prototype._setupListeners = function(name, mediaQuery) { 152 | if (!window.matchMedia) return; 153 | 154 | var mql = window.matchMedia(mediaQuery); 155 | mql._fn = function (e) { 156 | return this._handleMediaQueryChange(e.matches, name); 157 | }.bind(this); 158 | mql.addListener(mql._fn); 159 | 160 | return mql; 161 | }; 162 | 163 | MediaListener.prototype._handleMediaQueryChange = function(matches, name) { 164 | if (matches) { 165 | return this.changeHandler(name); 166 | } 167 | }; 168 | 169 | module.exports = MediaListener; 170 | 171 | 172 | /***/ }, 173 | /* 3 */ 174 | /***/ function(module, exports) { 175 | 176 | 'use strict'; 177 | /* eslint-disable no-unused-vars */ 178 | var hasOwnProperty = Object.prototype.hasOwnProperty; 179 | var propIsEnumerable = Object.prototype.propertyIsEnumerable; 180 | 181 | function toObject(val) { 182 | if (val === null || val === undefined) { 183 | throw new TypeError('Object.assign cannot be called with null or undefined'); 184 | } 185 | 186 | return Object(val); 187 | } 188 | 189 | function shouldUseNative() { 190 | try { 191 | if (!Object.assign) { 192 | return false; 193 | } 194 | 195 | // Detect buggy property enumeration order in older V8 versions. 196 | 197 | // https://bugs.chromium.org/p/v8/issues/detail?id=4118 198 | var test1 = new String('abc'); // eslint-disable-line 199 | test1[5] = 'de'; 200 | if (Object.getOwnPropertyNames(test1)[0] === '5') { 201 | return false; 202 | } 203 | 204 | // https://bugs.chromium.org/p/v8/issues/detail?id=3056 205 | var test2 = {}; 206 | for (var i = 0; i < 10; i++) { 207 | test2['_' + String.fromCharCode(i)] = i; 208 | } 209 | var order2 = Object.getOwnPropertyNames(test2).map(function (n) { 210 | return test2[n]; 211 | }); 212 | if (order2.join('') !== '0123456789') { 213 | return false; 214 | } 215 | 216 | // https://bugs.chromium.org/p/v8/issues/detail?id=3056 217 | var test3 = {}; 218 | 'abcdefghijklmnopqrst'.split('').forEach(function (letter) { 219 | test3[letter] = letter; 220 | }); 221 | if (Object.keys(Object.assign({}, test3)).join('') !== 222 | 'abcdefghijklmnopqrst') { 223 | return false; 224 | } 225 | 226 | return true; 227 | } catch (e) { 228 | // We don't expect any of the above to throw, but better to be safe. 229 | return false; 230 | } 231 | } 232 | 233 | module.exports = shouldUseNative() ? Object.assign : function (target, source) { 234 | var from; 235 | var to = toObject(target); 236 | var symbols; 237 | 238 | for (var s = 1; s < arguments.length; s++) { 239 | from = Object(arguments[s]); 240 | 241 | for (var key in from) { 242 | if (hasOwnProperty.call(from, key)) { 243 | to[key] = from[key]; 244 | } 245 | } 246 | 247 | if (Object.getOwnPropertySymbols) { 248 | symbols = Object.getOwnPropertySymbols(from); 249 | for (var i = 0; i < symbols.length; i++) { 250 | if (propIsEnumerable.call(from, symbols[i])) { 251 | to[symbols[i]] = from[symbols[i]]; 252 | } 253 | } 254 | } 255 | } 256 | 257 | return to; 258 | }; 259 | 260 | 261 | /***/ } 262 | /******/ ]) 263 | }); 264 | ; -------------------------------------------------------------------------------- /react_media_queryable.min.js: -------------------------------------------------------------------------------- 1 | !function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(require("react")):"function"==typeof define&&define.amd?define(["react"],t):"object"==typeof exports?exports.MediaQueryable=t(require("react")):e.MediaQueryable=t(e.React)}(this,function(e){return function(e){function t(n){if(r[n])return r[n].exports;var i=r[n]={exports:{},id:n,loaded:!1};return e[n].call(i.exports,i,i.exports,t),i.loaded=!0,i.exports}var r={};return t.m=e,t.c=r,t.p="",t(0)}([function(e,t,r){var n=r(1),i=r(2),o=r(3);e.exports=n.createClass({displayName:"MediaQueryable",mediaListener:null,propTypes:{className:n.PropTypes.string,defaultMediaQuery:n.PropTypes.string.isRequired,mediaQueries:n.PropTypes.object.isRequired,style:n.PropTypes.object},getInitialState:function(){return{mediaQuery:void 0}},componentDidMount:function(){this.mediaListener=new i(this.props.mediaQueries,this._onMediaQueryChange)},componentWillUnmount:function(){this.mediaListener&&this.mediaListener.stopListening()},render:function(){var e=this._currentMediaQuery();if(!e)return null;var t=n.Children.map(this.props.children,function(e){if(null!==e)return n.cloneElement(e,{mediaQuery:this._currentMediaQuery()})},this);return n.DOM.div(o({},{children:t,className:this.props.className,style:this.props.style}))},_currentMediaQuery:function(){return this.state.mediaQuery||this.props.defaultMediaQuery||null},_onMediaQueryChange:function(e){this.setState({mediaQuery:e})}})},function(t,r){t.exports=e},function(e,t){function r(e,t){this.changeHandler=t,this.mqls=this._buildMediaQueryLists(e)}r.prototype.stopListening=function(){var e;for(e in this.mqls){var t=this.mqls[e];t.removeListener&&t.removeListener(t._fn)}},r.prototype._buildMediaQueryLists=function(e){if(!window.matchMedia)return{};var t,r={};for(t in e){var n=this._setupListeners(t,e[t]);r[t]=n,this._handleMediaQueryChange(n.matches,t)}return r},r.prototype._setupListeners=function(e,t){if(window.matchMedia){var r=window.matchMedia(t);return r._fn=function(t){return this._handleMediaQueryChange(t.matches,e)}.bind(this),r.addListener(r._fn),r}},r.prototype._handleMediaQueryChange=function(e,t){if(e)return this.changeHandler(t)},e.exports=r},function(e,t){"use strict";function r(e){if(null===e||void 0===e)throw new TypeError("Object.assign cannot be called with null or undefined");return Object(e)}function n(){try{if(!Object.assign)return!1;var e=new String("abc");if(e[5]="de","5"===Object.getOwnPropertyNames(e)[0])return!1;for(var t={},r=0;r<10;r++)t["_"+String.fromCharCode(r)]=r;var n=Object.getOwnPropertyNames(t).map(function(e){return t[e]});if("0123456789"!==n.join(""))return!1;var i={};return"abcdefghijklmnopqrst".split("").forEach(function(e){i[e]=e}),"abcdefghijklmnopqrst"===Object.keys(Object.assign({},i)).join("")}catch(o){return!1}}var i=Object.prototype.hasOwnProperty,o=Object.prototype.propertyIsEnumerable;e.exports=n()?Object.assign:function(e,t){for(var n,s,a=r(e),u=1;u