-
-
Save akolybelnikov/353848d4826639cc7f2c6ad32c0174f0 to your computer and use it in GitHub Desktop.
React based
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
## 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