Miss any of our Open RFC calls?Watch the recordings here! »

react-simple-media-mixin

0.1.0 • Public • Published

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

Install

npm i react-simple-media-mixin

DownloadsWeekly Downloads

3

Version

0.1.0

License

MIT

Last publish

Collaborators

  • avatar