r/javascript • • Aug 21 '18

Effectively supported in all browsers, JavaScript has its own form of media queries just like CSS.

https://developer.mozilla.org/en-US/docs/Web/API/Window/matchMedia
465 Upvotes

114 comments sorted by

View all comments

2

u/atubofsoup Aug 24 '18

Just learned about this in one of my last projects and wrote a react HoC that takes a breakpoints object, adds listeners, re-renders when breakpoints change, and passes the active breakpoints to the wrapped component:

function responsive(breakpoints) {
  return Wrapped => class Responsive extends React.Component {
    state = Object.keys(breakpoints).reduce((breakpointValues, key) => {
      breakpointValues[key] = false;
      return breakpointValues;
    }, {});

    constructor(props) {
      super(props);
      this._queryList = Object.entries(breakpoints).map(([key, breakpoint]) => {
        const query = window.matchMedia(breakpoint);
        query._key = key;
        query.addListener(this.computeBreakpointMatches);
        return query;
      });
      this.computeBreakpointMatches();
    }

    computeBreakpointMatches = () => {
      const { state } = this;
      const newState = {};
      let changed = false;
      for(let query of this._queryList) {
        const key = query._key;
        const { matches } = query;
        if(state[key] !== matches) {
          changed = true;
          newState[key] = matches; 
        }
      }
      if(changed) this.setState(newState);
    };

    componentWillUnmount() {
      for(let query of this._queryList) {
        query.removeListener(this.computeBreakpointMatches);
      }
    }

    render() {
      return (<Wrapped {...this.props} breakpoints={this.state}/>);
    }
  };
}

@responsive({
  large: 'screen and (min-width: 1100px)',
  medium: 'screen and (min-width: 700px) and (max-width: 1099px)',
  small: 'screen and (max-width: 699px)',
})
class MyComponent extends Component {
  render() {
    const { breakpoints } = this.props;
    if(breakpoints.small) return (<div>Small</div>);
    if(breakpoints.medium) return (<div>Medium</div>);
    return (<div>Large</div>);
  }
}