Last active
October 16, 2018 16:50
-
-
Save olecksamdr/b82f9aa7944001621e1248db7e9ae19a to your computer and use it in GitHub Desktop.
A HOC which receive media query string, and hide wrapped component when this window size matches this media query
This file contains hidden or 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
export const SIZES = { | |
small: 768, | |
medium: 1024, | |
large: 1200, | |
}; |
This file contains hidden or 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
import React, { Component } from 'react'; | |
const hideOn = mediaQuery => WrappedComponent => class extends Component { | |
constructor(props) { | |
super(props); | |
this.state = { | |
isHidden: window.matchMedia(mediaQuery).matches, | |
}; | |
} | |
componentDidMount() { | |
this.mql = window.matchMedia(mediaQuery); | |
this.mql.addListener(this.handleMedia); | |
} | |
componentWillUnmount() { | |
this.mql.removeListener(this.handleMedia); | |
} | |
render() { | |
return this.state.isHidden ? null : <WrappedComponent {...this.props} />; | |
} | |
handleMedia = (mql) => { | |
this.setState({ isHidden: mql.matches }); | |
} | |
}; | |
export default hideOn; |
This file contains hidden or 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
import { SIZES } from 'const/media'; | |
export const smallAndUp = `(min-width: ${SIZES.small / 16}em)`; | |
export const smallAndDown = `(max-width: ${SIZES.small / 16}em)`; | |
export const mediumAndUp = `(min-width: ${SIZES.medium / 16}em)`; | |
export const mediumAndDown = `(max-width: ${SIZES.medium / 16}em)`; | |
export const largeAndUp = `(min-width: ${SIZES.large / 16}em)`; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example: