Learn about our RFC process, Open RFC meetings & more.Join in the discussion! »

react-mixin-media-query

0.1.2 • Public • Published

React mixin to handle media queries

Provides a hook to handle media queries in react.

It's NOT a component (see panquish package for this).

It depends on the excellent media-query-facade package.

Installation

npm install react-mixin-media-query --save

Basic Usage

var
  React    = require('react'),
  MQFacade = require('react-mixin-media-query').facade,
  MQMixin  = require('react-mixin-media-query').mixin
;

// config media-query-facade
var RFConfig = {
  MQFacadeConfig: {
    small: 'only screen and (max-width: 40em)',
    large: 'only screen and (min-width: 40em)'
  },
  /**
   * @returns {MQFacade}
   */
  getMQFacade: function() {
    return new MQFacade(this.MQFacadeConfig);
  }
};

// create component
var ReactComponent = React.createClass({
  mixins: [MQMixin],
  getInitialState: function () {
    return {
      mqCurrentRule: 'small'
    };
  },
  
  /**
   * Needed for MQMixin
   * @returns {{rule: string, callback: function}[]}
   */
  getMediaQueryRules: function() {
    return [
      {rule: 'small',  callback: this.changeMQRule.bind(this, 'small')  },
      {rule: 'large',  callback: this.changeMQRule.bind(this, 'large')  }
    ]
  },
  
  /**
   * The method called when the media query rules change
   */
  changeMQRule: function(currentRule) {
    this.setState({mqCurrentRule: currentRule});
  },
  
  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-mixin-media-query

DownloadsWeekly Downloads

2

Version

0.1.2

License

MIT

Last publish

Collaborators

  • avatar