Created
April 4, 2019 00:59
-
-
Save KennyHammerlund/9ce4e2592487e921d1d4bb36770c0ccf to your computer and use it in GitHub Desktop.
React-Emotion Mounting in a new window. When this component is mounted it creates a new window with an instance of React-Emotion attached to it.
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
import ReactDOM from "react-dom"; | |
import React from "react"; | |
import ScoreSheetLayout from "./scoresheetLayout"; | |
import createEmotionStyled from "create-emotion-styled"; | |
import createEmotion from "create-emotion"; | |
class Portal extends React.PureComponent { | |
constructor(props) { | |
super(props); | |
this.containerEl = null; | |
this.externalWindow = null; | |
this.styled = null; | |
} | |
componentDidMount() { | |
const { matchId } = this.props; | |
this.externalWindow = window.open( | |
"", | |
`Scoresheet for match ${matchId || "n/a"}`, | |
"width=1000,height=1250,left=400,top=400" | |
); | |
this.containerEl = this.externalWindow.document.createElement("div"); | |
this.externalWindow.document.body.appendChild(this.containerEl); | |
this.containerEl.setAttribute("id", "app"); | |
// Set emotion instance to the created app container | |
const emotionContainer = this.externalWindow.document.createElement("div"); | |
emotionContainer.id = "emotion"; | |
this.externalWindow.document.body.insertBefore( | |
emotionContainer, | |
this.externalWindow.document.getElementById("app") | |
); | |
// Creates an instance of emotion & styled atached to the emotion element | |
const created = createEmotion({ | |
container: this.externalWindow.document.getElementById("emotion") | |
}); | |
this.styled = createEmotionStyled(created, React); | |
this.setMounted(); | |
} | |
setMounted = () => { | |
this.setState({ mounted: true }); | |
}; | |
componentWillUnmount() { | |
this.externalWindow.close(); | |
} | |
render() { | |
if (!this.containerEl) { | |
return null; | |
} | |
// Since the emotion instance is not created until the component mounts | |
// we cant export the styled component. We pass it down the tree instead | |
return ReactDOM.createPortal( | |
<ScoreSheetLayout styled={this.styled} />, | |
this.containerEl | |
); | |
} | |
} | |
export default Portal; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment