react-simple-media-mixin
v0.1.0
Published
Simple react mixin to handle media queries (with fallback for node environment)
Downloads
5
Maintainers
Readme
Real simple React mixin to handle media queries
Provides a media
attribute for your react components & a fallback for server rendering.
It's NOT a component (see panquish package for this).
Installation
npm install react-simple-media-mixin --save
Basic Usage
var
React = require('react'),
MediaQueryMixin = require('react-simple-media-mixin')
;
// create component
var ReactComponent = React.createClass({
mixins: [MediaQueryMixin],
getInitialState: function () {
return {
mqCurrentRule: 'small'
};
},
componentWillMount: function() {
var self = this;
var mediaQueryRules = [
{query: 'only screen and (max-width: 40em)', callback: function() {self.setState({mqCurrentRule: 'small'});}},
{query: 'only screen and (min-width: 40.063em)', callback: function() {self.setState({mqCurrentRule: 'medium'});}}
];
mediaQueryRules.map(function(rule) {
var match = self.media.match(rule.query);
// init
if(match.matches) {
rule.callback();
}
// listener
match
.addListener(function(mq) {
if(mq.matches) {
rule.callback();
}
});
});
},
render: function() {
if(this.state.mqCurrentRule == 'small') {
return (
<div>I'm displayed only on small screens</div>
);
}
return (
<div>I do not appear on small screens</div>
);
}
});
React.renderComponent(
ReactComponent({config: config}),
document.body
);
Todo
- Tests ! :)
- Examples