I would like to render a react portal from a child component into a parent component using a ref created on the parent. I've tried to get this to work but in my experiments ReactDOM.createPortal()
fails to render anything.
Here is an example of what I am trying to accomplish: https://codesandbox.io/s/0qk3pxrkwn
Note that the text "I will render in my parent" is never rendered.
Am I doing something wrong here?
The context of this is that my child component is a dropdown, and my parent component wraps the child in overflow: hidden
in order to achieve some funky styles. To show the dropdown part of the child, I will need to render that content in the parent. Portals seem like a pretty good pattern for this use case.
From official portals doc:
Portals provide a first-class way to render children into a DOM node that exists outside the DOM hierarchy of the parent component.
If you'd like to do it anyway, do something like that in the parent component:
<ParentComponent>
<ChildWhichCreatesPortal />
<PortalContainer />
</ParentComponent>
where PortalContainer
is something which never rerenders:
class PortalContainer extends React.Component {
shouldComponentUpdate() {
return false
}
render() {
<div id="id-to-find-dom-node"></div>
}
}
The way I specified above should work, but I didn't try
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With