Created
July 14, 2017 13:02
-
-
Save dglowinski/544532b1c2cb22f9d28b235c980ebb68 to your computer and use it in GitHub Desktop.
React - media query component
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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