react-responsive-decorator

Higher order component wrapper / decorator around enquire for developing responsive react components

Downloads in past

Stats

StarsIssuesVersionUpdatedCreatedSize
react-responsive-decorator
0.0.17 years ago7 years agoMinified + gzip package size for react-responsive-decorator in KB

Readme

react-responsive-decorator
react-responsive-decorator makes building responsive components easy. Adapted from https://github.com/akiran/react-responsive-mixin

This higher-order component / decorator adds a method called media() to the react component. This is a wrapper around enquire.js
NOTE: This library assumes you're using Babel >= 5, with either a) stage set to 0; or b) have the experimental transformers classProperties and decorators turned on. See https://babeljs.io/docs/usage/experimental/ for more information.
For more information on ES7 decorators, see: https://github.com/wycats/javascript-decorators

Usage

this.props.media(query, handler)
query
query is a media query definition either in string or object format. This mixin internally uses json2mq to convert media query from object to string format.
handler
handler is a function that needs to be executed when media query matches. handler can also be an object according to enquire.js API
Example
Simply add a @Responsive decorator annotation at the top of your class like so:
import React from 'react';
import Responsive from 'react-responsive-decorator';

@Responsive
class MyComponent extends React.Component {

  state = {
    isMobile: false
  }

  componentDidMount() {
    this.props.media({ minWidth: 768 }, () => {
      this.setState({
        isMobile: false
      });
    });

    this.props.media({ maxWidth: 768 }, () => {
      this.setState({
        isMobile: true
      });
    });
  }

  render() {
    const { isMobile } = this.state;

    return (
      <div>
        {isMobile ?
          <div>Mobile</div> :
          <div>Not mobile</div>
        }
      </div>
    );
  }
}

export default MyComponent;

Or, if you'd rather return a wrapped, Higher Order component, export like so:
import React from 'react';
import Responsive from 'react-responsive-decorator';

class MyComponent extends React.Component {
  (...)
}

export default Responsive(MyComponent);
Credits
This code has been adapted from https://github.com/akiran/react-responsive-mixin in order to remove the mixin dependency.