Advertisement
Guest User

Untitled

a guest
Jul 25th, 2017
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.96 KB | None | 0 0
  1. /* globals matchMedia */
  2. import React, { PureComponent } from 'react';
  3.  
  4. function adaptiveComponent(mediaQueries) {
  5. const firstMatchingQuery = Object.keys(mediaQueries).find(mediaQuery =>
  6. matchMedia(mediaQuery).matches);
  7.  
  8. if (!firstMatchingQuery) {
  9. throw new Error(`No media query matches found in ${mediaQueries}`);
  10. }
  11.  
  12. class AdaptiveComponent extends PureComponent {
  13. state = {
  14. Component: null,
  15. }
  16.  
  17. componentWillMount() {
  18. mediaQueries[firstMatchingQuery].then(Component =>
  19. this.setState({ Component: Component.default || Component })
  20. );
  21. }
  22.  
  23. render() {
  24. const { Component } = this.state;
  25. return Component ? <Component {...this.props} /> : null;
  26. }
  27. }
  28.  
  29. return AdaptiveComponent;
  30. }
  31.  
  32. export default adaptiveComponent;
  33.  
  34. // Usage:
  35.  
  36. export default adaptiveComponent({
  37. '(min-device-width: 1024px)': System.import('./component.desktop'),
  38. '(max-device-width: 1023px)': System.import('./component.mobile'),
  39. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement