From 57d09dbc41a2f4df5949e64416038e1f70d23fcd Mon Sep 17 00:00:00 2001 From: John Date: Wed, 20 Dec 2017 16:03:11 +0100 Subject: [PATCH] Fix Modal component to work on server side (#15) --- src/components/modal/modal.js | 32 +++++++++++++++++++++----------- 1 file changed, 21 insertions(+), 11 deletions(-) diff --git a/src/components/modal/modal.js b/src/components/modal/modal.js index ec05a568..32f94c71 100644 --- a/src/components/modal/modal.js +++ b/src/components/modal/modal.js @@ -32,27 +32,37 @@ export default class Modal extends PureComponent { static Content = ModalContent static Card = ModalCard - componentWillMount() { + state = { d: null } + + componentDidMount() { const d = this.getDocument(); - if (!this.portalElement && d) { - this.portalElement = d.createElement('div'); - this.portalElement.setAttribute('class', 'modal-container'); - d.body.appendChild(this.portalElement); - if (this.props.closeOnEsc) { - d.addEventListener('keydown', this.handleKeydown); - } + this.portalElement = d.createElement('div'); + this.portalElement.setAttribute('class', 'modal-container'); + d.body.appendChild(this.portalElement); + if (this.props.closeOnEsc) { + d.addEventListener('keydown', this.handleKeydown); } + // eslint-disable-next-line + this.setState({ d }); } componentWillUnmount() { + const { d } = this.state; if (this.props.closeOnEsc) { - const d = this.props.document || document; - d.addEventListener('keydown', this.handleKeydown); + d.removeEventListener('keydown', this.handleKeydown); } } /* istanbul ignore next */ - getDocument = () => this.props.document || document + getDocument = () => { + if (this.props.document) { + return this.props.document; + } + if (typeof document !== 'undefined') { + return document; + } + return null; + } portalElement = null;