All files InlinePortal.jsx

4.35% Statements 1/23
0% Branches 0/20
0% Functions 0/8
4.35% Lines 1/23
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 71 72 73 74 75 76 77 78 79 80 81 82            1x                                                                                                                                                      
import React from 'react';
import PropTypes from 'prop-types';
/* eslint-disable import/no-extraneous-dependencies */
import ReactDOM from 'react-dom';
/* eslint-enable import/no-extraneous-dependencies */
 
const isReact16 = ReactDOM.createPortal !== undefined;
 
export default class InlinePortal extends React.Component {
  static propTypes = {
    children: PropTypes.node,
    show: PropTypes.bool
  };
 
  static defaultProps = {
    children: null,
    show: false
  };
 
  componentDidMount() {
    this.renderFallbackPortal();
  }
 
  componentWillReceiveProps(nextProps) {
    if (nextProps.show) {
      this.createNode(nextProps);
    }
    if (nextProps.show === false && this.props.show === true) {
      this.closePortal();
    }
  }
 
  componentDidUpdate() {
    this.renderFallbackPortal();
  }
 
  componentWillUnmount() {
    this.closePortal();
  }
 
  createNode(props) {
    if (!this.node) {
      this.node = document.createElement('div');
      this.node.className = `${props.className || ''} portal`.trim();
      document.body.appendChild(this.node);
    }
  }
 
  closePortal() {
    if (this.node) {
      document.body.removeChild(this.node);
    }
    this.node = null;
  }
 
  /* eslint-disable consistent-return */
  renderFallbackPortal = () => {
    if (!isReact16) {
      if (this.props.show) {
        this.createNode(this.props);
        return ReactDOM.unstable_renderSubtreeIntoContainer(
          this,
          this.props.children,
          this.node
        );
      }
      this.closePortal();
    }
  };
  /* eslint-enable consistent-return */
 
  render() {
    if (!this.props.show || !isReact16) {
      return null;
    }
    return ReactDOM.createPortal(
      this.props.children,
      this.node
    );
  }
}