forked from ReactTraining/react-media
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMedia.js
58 lines (46 loc) · 1.21 KB
/
Media.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import React, { PropTypes } from 'react'
import json2mq from 'json2mq'
class Media extends React.Component {
state = {
matches: true
}
updateMatches = () =>
this.setState({ matches: this.mediaQueryList.matches })
componentWillMount() {
let { query } = this.props
if (typeof query !== 'string')
query = json2mq(query)
if (typeof window === 'object') {
this.mediaQueryList = window.matchMedia(query)
this.mediaQueryList.addListener(this.updateMatches)
this.updateMatches()
}
}
componentWillUnmount() {
this.mediaQueryList.removeListener(this.updateMatches)
}
render() {
const { children, render } = this.props
const { matches } = this.state
if (matches && render)
return render()
if (typeof children === 'function')
return children(matches)
return matches ? React.Children.only(children) : null
}
}
if (__DEV__) {
Media.propTypes = {
query: PropTypes.oneOfType([
PropTypes.string,
PropTypes.object,
PropTypes.arrayOf(PropTypes.object.isRequired)
]).isRequired,
render: PropTypes.func,
children: PropTypes.oneOfType([
PropTypes.node,
PropTypes.func
])
}
}
export default Media