Skip to content

Instantly share code, notes, and snippets.

@aliakakis
Last active December 4, 2018 07:50
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save aliakakis/27a4231ba653c24239ee758c05c8afba to your computer and use it in GitHub Desktop.
Save aliakakis/27a4231ba653c24239ee758c05c8afba 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