Skip to content

Instantly share code, notes, and snippets.

@dglowinski
Created July 14, 2017 13:02
Show Gist options
  • Save dglowinski/544532b1c2cb22f9d28b235c980ebb68 to your computer and use it in GitHub Desktop.
Save dglowinski/544532b1c2cb22f9d28b235c980ebb68 to your computer and use it in GitHub Desktop.
React - media query component
const PropTypes = require('prop-types');
class MediaQuery extends React.Component {
constructor(props) {
super(props);
this.state = {type:'desktop'};
}
getChildContext() {
return {type: this.state.type};
}
componentDidMount() {
const checkMediaQuery = () => {
const type = window.matchMedia("(min-width: 1025px)").matches ? 'desktop' : 'mobile';
if (type !== this.state.type) {
this.setState({type});
}
};
window.addEventListener('resize', checkMediaQuery);
checkMediaQuery();
}
render() {
return this.props.children;
}
}
MediaQuery.childContextTypes = {
type: PropTypes.string
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment