humanPursuit
11/27/2017 - 6:50 AM

ReactDOM portals Modal

// ReactDOM.createPortal(child, container)
// `child` is any renderable React child
// `container` is a dom element

const appRoot = document.getElementById('app-root');
const modalRoot = document.getElementById('modal-root');

class Modal extends React.Component {
  constructor(props) {
    super(props);
    this.el = document.createElement('div');
  }
  
  componentDidMount() {
    modalRoot.appendChild(this.el);
  }
  
  componentWillUnmount() {
    modalRoot.removeChild(this.el);
  }
  
  render() {
    return ReactDOM.createPortal(this.props.children, this.el);
  }
}


class Parent extends React.Component {
  // ...other code place here
  
  render() {
    return (
      <div>
        <Modal>
          child of modal
        </Modal>
      </div>
    );
  }
}

ReactDOM.render(<Parent />, appRoot);