Skip to content

Instantly share code, notes, and snippets.

@olecksamdr
Last active October 16, 2018 16:50
Show Gist options
  • Save olecksamdr/b82f9aa7944001621e1248db7e9ae19a to your computer and use it in GitHub Desktop.
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
export const SIZES = {
small: 768,
medium: 1024,
large: 1200,
};
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;
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)`;
@olecksamdr
Copy link
Author

olecksamdr commented Oct 16, 2018

Example:

// receive media query as string
const hideOnMaxWidth500 = hideOn('(max-width: 500px)');

// we can use media utils
const hideOnMobile = hideOn(smallAndDown);
const Logo = hideOnMobile(() => <img src="..." alt="..." />);

const Component = hideOn(mediumAndUp)(WrappedComponent)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment