Portalize
A component for injecting elements into React Portals via DOM selectors. You may
optionally choose to render your portals on the server side as well :)
Installation
yarn add react-portalize
or npm i react-portalize
Basic Usage
import Portalize from 'react-portalize'
<Portalize container='#portals'>
Hello
</Portalize>
<Portalize container='.portals'>
Hello
</Portalize>
<Portalize container='section'>
Hello
</Portalize>
<Portalize container='div[data-portalize="why not"]'>
Hello
</Portalize>
Example
Hello world
react-portalize
<Portalize container={string} children={React.Component}>
react-portalize/server
renderPortalsToString(html <string>)
- Injects portals created within your App into their respective containers.
You can provide either your entire
<!DOCTYPE html>
string here or
alternatively just the React root generated by
ReactDOMServer.renderToString()
.
Server side rendering
Example with React root as the entry point
import {renderPortalsToString} from 'react-portalize/server'
function serverRenderer req, res, next() {
const page = renderPortalsToString(
ReactDOMServer.renderToString(<App/>)
)
res.set('Content-Type', 'text/html').send(`
<!DOCTYPE html>
<html lang="en">
<head>
<title>Hello world app</title>
</head>
<body>
<div id="⚛️">${page}</div>
</body>
</html>
`)
}
Example with HTML root as the entry point
import {renderPortalsToString} from 'react-portalize/server'
function serverRenderer (req, res, next) {
const page = ReactDOMServer.renderToString(<App/>)
res.set('Content-Type', 'text/html').send(
renderPortalsToString(`
<!DOCTYPE html>
<html lang="en">
<head>
<title>Hello world app</title>
</head>
<body>
<div id="⚛️">${page}</div>
</body>
</html>
`)
)
}
Note
You will receive a warning message in the console from ReactDOM.hydrate()
in
"development" akin to Did not expect server HTML to contain the text node "Hello" in <div>.
.
This is because ReactDOM.hydrate()
does not expect your portals to be rendered
into the App. You can safely ignore this warning.
Future
renderPortalsToNodeStream()