Skip to content

Instantly share code, notes, and snippets.

Created August 25, 2016 13:03
Show Gist options
  • Save anonymous/69a8de26684af1542314e807b04e4526 to your computer and use it in GitHub Desktop.
Save anonymous/69a8de26684af1542314e807b04e4526 to your computer and use it in GitHub Desktop.
A React HoC to handle media queries.

This bit of code gets a queryList and Component passed to it.

Use it like: const MediaMatchingComponent = mediaQueryHoc(queryList, MyComponent);

A queryList is the return of something like window.matchMedia('(max-width: 50rem)');

const React = require('react');
const mediaQueryHoc = function(queryList, Component) {
class AddMediaQuery extends React.Component {
constructor(props) {
super(props);
this.state = {
mediaQueryMatches: false,
};
this.handleScreenChange = this.handleScreenChange.bind(this);
}
handleScreenChange() {
if(queryList.matches !== this.state.isSmallScreen) {
this.setState({
mediaQueryMatches: queryList.matches,
});
}
}
componentWillMount() {
if(queryList.matches) {
this.setState({
mediaQueryMatches: true,
});
}
queryList.addListener(this.handleScreenChange);
}
componentWillUnmount() {
queryList.removeListener(this.handleScreenChange);
}
render() {
return(
<Component {...this.props} mediaQueryMatches={this.state.mediaQueryMatches} />
);
}
}
return AddMediaQuery;
};
module.exports = mediaQueryHoc;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment