Created
September 2, 2017 23:38
-
-
Save hamlim/27760f52a64d4c92680fb32bb118b95b to your computer and use it in GitHub Desktop.
React and Old App Interop
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
/* | |
Lets say you want to adopt react into an old app that is using some other framework | |
without re-writing all of the app in one go you decide to go step by step. | |
Now lets also say that you want to be able to compose the entire app in one | |
component/state tree. However you have a chunk of it that you know you don't want to | |
change over just yet: | |
<Old App> | |
<New React Feature /> | |
<Old Feature that would be too difficult to convert now /> | |
<Some other New React Feature /> | |
</Old App> | |
You could make two calls to `ReactDom.render` to get the app to render all there, | |
or you can use a portal and compose the component tree all at once: | |
<Old App> | |
<New React Feature Container> | |
<New Feature A /> | |
<Portal> | |
<New Feature B /> | |
</Portal> | |
</New React Feature Container> | |
<Old Feature /> | |
<div id="mount point for new feature b" /> | |
</Old App> | |
*/ | |
const newTarget = "#new-app-part-2"; | |
/* | |
example HTML setup: | |
<div> | |
<div id="reactMount"></div> | |
<div id="Old App mount"> .... </div> | |
<div id="new-app-part-2"></div> | |
</div> | |
*/ | |
const TopLevelApp = () => ( | |
<div> | |
<h2>This is feature A</h2> | |
<Portal to={newTarget}> | |
<h3>This is feature B</h3> | |
</Portal> | |
</div> | |
); | |
render(<TopLevelApp />, document.getElementById("root")); |
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 React, { Component } from 'react'; | |
import { unstable_createPortal as createPortal } from 'react-dom'; | |
export default class Portal extends Component { | |
render() { | |
return this.props.to && createPortal(this.props.children, this.props.to); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment