Skip to content

Instantly share code, notes, and snippets.

@olecksamdr
Created February 19, 2019 08:47
Show Gist options
  • Save olecksamdr/8766749e2116286a0528b881ad2a3e96 to your computer and use it in GitHub Desktop.
Save olecksamdr/8766749e2116286a0528b881ad2a3e96 to your computer and use it in GitHub Desktop.
Media component
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