Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* 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'),
- });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement