react-mixin-media-query

React mixin to handle media queries ===

Usage no npm install needed!

<script type="module">
  import reactMixinMediaQuery from 'https://cdn.skypack.dev/react-mixin-media-query';
</script>

README

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('facade'),
  MQMixin  = require('react-mixin-media-query')
;

// 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