UNPKG

fk-react-ui-components

Version:

Step 1 : Create a file in [ Seeds / Plants / Trees ] <br> Step 2 : It should export an Object with component name and story Component [Refer other components] <br> Step 3 : Story Component should return a react component <br> Step 3 : Created file should

75 lines (64 loc) 1.58 kB
import React from 'react'; import ReactDOM from 'react-dom'; import { PropTypes } from 'prop-types'; export default class Portal extends React.PureComponent { componentDidMount() { this.renderLayer(); } componentDidUpdate() { this.renderLayer(); } componentWillUnmount() { this.unrenderLayer(); } /** * Returns the layer in which children will be rendered */ getLayer = () => { if (!this.layer) { this.layer = document.createElement('div'); if (document.body && this.layer) { document.body.appendChild(this.layer); } } return this.layer; }; /** * Removes the previously rendered layer */ unrenderLayer = () => { if (this.layer) { document.body.removeChild(this.layer); this.layer = null; } }; /** * Renders the children inside the layer */ renderLayer() { const { children, open } = this.props; if (open) { const layerElement = React.Children.only(children); ReactDOM.unstable_renderSubtreeIntoContainer( this, layerElement, this.getLayer() ); } else { this.unrenderLayer(); } } render() { return null; } } Portal.propTypes = { children: PropTypes.element.isRequired, /** * Renders the children at body level */ open: PropTypes.bool }; Portal.defaultProps = { open: false };