Skip to content

Instantly share code, notes, and snippets.

@akolybelnikov
Forked from aliakakis/match-media.js
Created December 4, 2018 07:50
Show Gist options
  • Save akolybelnikov/353848d4826639cc7f2c6ad32c0174f0 to your computer and use it in GitHub Desktop.
Save akolybelnikov/353848d4826639cc7f2c6ad32c0174f0 to your computer and use it in GitHub Desktop.
React based
/*
## Example ##
<MatchMedia mediaWidth={["(min-width: 768px)", "(min-width: 1280px)"]}>
<Checkbox
id="check_1"
label="Hello World!"
checked={isChecked}
onChange={() => this.setState({ isChecked: !isChecked })}
/>
</MatchMedia>
*/
import React, { Component } from "react";
import PropTypes from "prop-types";
export default class MatchMedia extends Component {
constructor(props) {
super(props);
this.state = {
isMatch: false
};
}
componentDidMount() {
const { handleMatchMediaOnResize } = this;
handleMatchMediaOnResize();
window.addEventListener("resize", handleMatchMediaOnResize, false);
}
handleMatchMediaOnResize = () => {
const { mediaWidth } = this.props;
mediaWidth.forEach(width => {
this.setState({ isMatch: window.matchMedia(width).matches });
});
};
render() {
const { children, tag, className } = this.props;
const { isMatch } = this.state;
const Component = tag;
return isMatch && <Component className={className}>{children}</Component>;
}
}
MatchMedia.defaultProps = {
tag: "div",
className: "",
mediaWidth: []
};
MatchMedia.propTypes = {
tag: PropTypes.string,
className: PropTypes.string,
mediaWidth: PropTypes.arrayOf(PropTypes.string)
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment