React Element Portal
Render a React component inline, but target a DOM element (or elements) by id or selector.
Why?
If you're making a shiny new React app where you use React everywhere, for every page, and for the entirety of every page, then you probably don't need this. But if you live in an imperfect world, where you have a server-generated header/footer or some static blog pages, or anything else not fully controlled by React, you can use an ElementPortal
to control those things from inside a single root React element.
Install
npm install react-element-portal --save
Usage with vanilla React
Let's say we get this from the server:
<!-- Header generated by server --> Home My Sorta Cool App Joe <!-- Container for React to do its thing -->
Even though we don't control the header, we can pretend like parts of it are owned by a single React root element.
; ReactDOM;
You can also use a selector instead of an id.
<ElementPortal selector=".header .user"> <div> ... </div></ElementPortal>
Additional features
Reset styling
The resetAttributes
prop can be used to remove any attributes from the DOM node we are rendering to:
// All styles and classes from the node with id "header" will be cleared<ElementPortal id="header" resetAttributes='class' 'style'> <div className="some-other-class"> ... </div></ElementPortal>
View property
ElementPortal
also accepts an optional view
prop that takes a component, to be rendered inside the portal:
<ElementPortal id="header" view=CoolHeaderComponent />
One advantage of using the view
prop is the ability to derive properties from the original DOM node and pass them to the the component.
Let's say our original DOM element already contains some useful data:
Joe
And we would like to render the following component:
const CoolGreeting = <div>Welcome <a href=`/profile/`>name!</a></div>
By using the mapNodeToProps
prop, you can easily pass this data like so:
; const mapNodeToProps = name: nodetextContent ...; ReactDOM;
Usage as Higher Order Component
ElementPortal
can also be used as a HOC:
;; const MyComponentWithPortal = ; ReactDOM;
or composing with other HOC's:
;; const MyComponent = <h1>Hello propsname!</h1>; const MyComposedComponent = MyComponent;
Passing context to your ElementPortal
Context from your main tree is passed down automatically to your ElementPortal
. For example, if you use Redux, the store
context will not get lost, and using connect
will behave as expected in the children of your ElementPortal
.