Created
July 31, 2014 10:04
-
-
Save dittos/a5550bfbf9cecff2aa22 to your computer and use it in GitHub Desktop.
React-Popup
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** @jsx React.DOM */ | |
import React from 'react'; | |
var popupId = 0; | |
function addStyle(doc, cssCode) { | |
var styleElement = doc.createElement("style"); | |
styleElement.type = "text/css"; | |
var head = doc.getElementsByTagName("head")[0]; | |
head.appendChild(styleElement); | |
if (styleElement.styleSheet) { | |
styleElement.styleSheet.cssText = cssCode; | |
} else { | |
styleElement.appendChild(doc.createTextNode(cssCode)); | |
} | |
} | |
export default PopupView = React.createClass({ | |
render() { | |
return null; | |
}, | |
componentWillUnmount() { | |
this.close(); | |
}, | |
componentDidUpdate() { | |
if (this._isOpen()) { | |
this._renderToPopup(); | |
} | |
}, | |
open() { | |
if (this._isOpen()) { | |
return; | |
} | |
popupId++; | |
var features = 'width=' + this.props.width + ',height=' + this.props.height; | |
this._popup = window.open('about:blank', 'popup' + popupId, features); | |
if (this.props.stylesheets) { | |
this.props.stylesheets.forEach(cssCode => addStyle(this._popup.document, cssCode)); | |
} | |
this._popup.addEventListener('close', this.props.onClose); | |
this._renderToPopup(); | |
}, | |
close() { | |
if (this._isOpen()) { | |
this._popup.close(); | |
this._clearPopup(); | |
} | |
}, | |
_isOpen() { | |
if (this._popup && this._popup.closed) { | |
this._clearPopup(); | |
} | |
return Boolean(this._popup); | |
}, | |
_renderToPopup() { | |
React.renderComponent(<div>{this.props.children}</div>, this._popup.document.body); | |
}, | |
_clearPopup() { | |
React.unmountComponentAtNode(this._popup.document.body); | |
this._popup = null; | |
this.props.onClose && this.props.onClose(); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment