react-micro-match-media
Version:
> zero dependencies, ~1kb render prop wrapper of window.matchMedia
2 lines (1 loc) • 2.28 kB
JavaScript
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t(require("react")):"function"==typeof define&&define.amd?define(["react"],t):e.ReactMicroMatchMedia=t(e.React)}(this,function(e){"use strict";e=e&&e.hasOwnProperty("default")?e.default:e;var t=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")},n=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),r=function(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t};return function(o){function i(){var e,n,o;t(this,i);for(var a=arguments.length,u=Array(a),c=0;c<a;c++)u[c]=arguments[c];return n=o=r(this,(e=i.__proto__||Object.getPrototypeOf(i)).call.apply(e,[this].concat(u))),o.canUseDOM=!("undefined"==typeof window),o.state={query:o.props.query,matches:!!o.canUseDOM&&window.matchMedia(o.props.query).matches},o.matchMediaListener=function(e){var t=e.matches;o.setState({matches:t})},r(o,n)}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}(i,e.Component),n(i,[{key:"addListener",value:function(e){window.matchMedia(e).addListener(this.matchMediaListener)}},{key:"removeListener",value:function(e){window.matchMedia(e).removeListener(this.matchMediaListener)}},{key:"componentDidUpdate",value:function(e,t){var n=this.state.query;t.query!==n&&(this.removeListener(n),this.addListener(n))}},{key:"componentDidMount",value:function(){this.addListener(this.props.query)}},{key:"componentWillUnmount",value:function(){this.removeListener(this.props.query)}},{key:"render",value:function(){return this.props.children(this.state.matches)}}],[{key:"getDerivedStateFromProps",value:function(e,t){return e.query!==t.query?{query:e.query,matches:window.matchMedia(e.query).matches}:null}}]),i}()});