Last active
February 2, 2019 19:43
-
-
Save dominictobias/70c6e548f456be1e98b351f7d57756cc to your computer and use it in GitHub Desktop.
Loading different components at runtime depending on media queries in React
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
/* 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