All files / atoms/Visible Visible.jsx

18.51% Statements 5/27
0% Branches 0/6
0% Functions 0/11
21.73% Lines 5/23

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70                1x                                                                                                   1x       1x     1x 1x      
import React, { Component } from 'react';
import PropTypes from 'prop-types';
 
import Context from '../../Theme/Context';
import Atom from '../Atom';
 
import match from '../../util/matchMedia';
 
const mediaToString = mediaArray => mediaArray.join(', ');
 
class Visible extends Component {
  isMounted = false;
 
  componentDidMount() {
    this.isMounted = true;
    this.forceUpdate();
    window.addEventListener('resize', this.handleResize, { passive: true });
  }
 
  componentWillUnmount() {
    this.isMounted = false;
    window.removeEventListener('resize', this.handleResize, true);
  }
 
  get clientQueries() {
    const { children, element, ...queryNames } = this.props;
    return Object.keys(queryNames).map(name => this.context.theme.mediaQueries[name]);
  }
 
  get serverQueries() {
    return this.clientQueries.map(query => `not ${query}`);
  }
 
  get clientContent() {
    const mq = mediaToString(this.clientQueries);
    const { children } = this.props;
    return match(mq) ? children : null;
  }
 
  get serverContent() {
    const { children, element } = this.props;
    const mq = `@media ${mediaToString(this.serverQueries)}`;
    return (
      <Atom css={{ [mq]: { display: 'none' } }} element={element}>
        {children}
      </Atom>
    );
  }
 
  handleResize = () => {
    if (this.isMounted) this.forceUpdate();
  };
 
  render() {
    return this.isMounted ? this.clientContent : this.serverContent;
  }
}
 
Visible.propTypes = {
  children: PropTypes.node.isRequired,
  element: PropTypes.string,
};
Visible.defaultProps = {
  element: 'div',
};
Visible.displayName = 'Visible';
Visible.contextType = Context;
 
export default Visible;