Skip to content

Instantly share code, notes, and snippets.

@sekoyo
Last active February 2, 2019 19:43
Show Gist options
  • Save sekoyo/70c6e548f456be1e98b351f7d57756cc to your computer and use it in GitHub Desktop.
Save sekoyo/70c6e548f456be1e98b351f7d57756cc to your computer and use it in GitHub Desktop.
Loading different components at runtime depending on media queries in React
/* globals matchMedia */
import React, { PureComponent } from 'react';
function adaptiveComponent(mediaQueries) {
const firstMatchingQuery = Object.keys(mediaQueries).find(mediaQuery =>
matchMedia(mediaQuery).matches);
if (!firstMatchingQuery) {
throw new Error(`No media query matches found in ${mediaQueries}`);
}
class AdaptiveComponent extends PureComponent {
state = {
Component: null,
}
componentWillMount() {
mediaQueries[firstMatchingQuery].then(Component =>
this.setState({ Component: Component.default || Component })
);
}
render() {
const { Component } = this.state;
return Component ? <Component {...this.props} /> : null;
}
}
return AdaptiveComponent;
}
export default adaptiveComponent;
// Usage:
export default adaptiveComponent({
'(min-device-width: 1024px)': System.import('./component.desktop'),
'(max-device-width: 1023px)': System.import('./component.mobile'),
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment