Created
February 19, 2019 08:47
-
-
Save olecksamdr/8766749e2116286a0528b881ad2a3e96 to your computer and use it in GitHub Desktop.
Media 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
import React, { Component } from 'react'; | |
import { arrayOf, node, oneOfType } from 'prop-types'; | |
class Media extends Component { | |
constructor(props) { | |
super(props); | |
this.state = { | |
matches: window.matchMedia(this.props.query).matches, | |
}; | |
} | |
componentDidMount() { | |
this.mql = window.matchMedia(this.props.query); | |
this.mql.addListener(this.handleMedia); | |
} | |
componentWillUnmount() { | |
this.mql.removeListener(this.handleMedia); | |
} | |
handleMedia = ({ matches }) => this.setState({ matches }); | |
render () { | |
return this.props.children(this.state.matches); | |
} | |
} | |
Media.propTypes = { | |
children: oneOfType([ | |
arrayOf(node), | |
node | |
]).isRequired | |
}; | |
export default Media; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment