import * as _ from "lodash"; import * as ReactDOM from "react-dom"; import * as React from "react"; interface IBodyScrollerProps { active?: boolean; } export class BodyScroller extends React.Component { public el: HTMLDivElement; constructor(props) { super(props); this.el = document.createElement('div'); this.el.id = "body-scroller"; } public componentDidMount() { if (this.props.active) { this.appendScroller(); } } public componentDidUpdate(prevProps: IBodyScrollerProps) { if (!prevProps.active && this.props.active) { this.appendScroller(); } else if (prevProps.active && !this.props.active) { this.removeScroller(); } } public componentWillUnmount() { this.removeScroller(); } public render() { return ReactDOM.createPortal( this.props.children, this.el ); } private appendScroller() { const bodyScrollers = document.body.querySelectorAll("#body-scroller"); if (!_.isEmpty(bodyScrollers)) { Array.from(bodyScrollers).forEach(bodyScroller => { document.body.removeChild(bodyScroller); }); } document.body.appendChild(this.el); } private removeScroller() { document.body.removeChild(this.el); } }