Skip to content
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 33 additions & 25 deletions modules/Media.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,39 @@ import MediaQueryList from "./MediaQueryList";
* Conditionally renders based on whether or not a media query matches.
*/
class Media extends React.Component {
constructor(props) {
super(props);

if (typeof window !== "object") return;

const targetWindow = props.targetWindow || window;

invariant(
typeof targetWindow.matchMedia === "function",
"<Media targetWindow> does not support `matchMedia`."
);

let { query } = props;
if (typeof query !== "string") query = json2mq(query);

this.mediaQueryList = new MediaQueryList(
targetWindow,
query,
this.updateMatches
);

const { matches } = this.mediaQueryList;

this.state = {
matches: matches && props.defaultMatches
};

const { onChange } = props;
if (onChange) {
onChange(matches);
}
}

static propTypes = {
defaultMatches: PropTypes.bool,
query: PropTypes.oneOfType([
Expand All @@ -26,10 +59,6 @@ class Media extends React.Component {
defaultMatches: true
};

state = {
matches: this.props.defaultMatches
};

updateMatches = () => {
const { matches } = this.mediaQueryList;

Expand All @@ -41,27 +70,6 @@ class Media extends React.Component {
}
};

componentWillMount() {
if (typeof window !== "object") return;

const targetWindow = this.props.targetWindow || window;

invariant(
typeof targetWindow.matchMedia === "function",
"<Media targetWindow> does not support `matchMedia`."
);

let { query } = this.props;
if (typeof query !== "string") query = json2mq(query);

this.mediaQueryList = new MediaQueryList(
targetWindow,
query,
this.updateMatches
);
this.updateMatches();
}

componentWillUnmount() {
this.mediaQueryList.cancel();
}
Expand Down