Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rendering from a child to a parent using refs and portals in React

Tags:

reactjs

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.

like image 534
Tom Avatar asked Sep 06 '25 14:09

Tom


1 Answers

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

like image 197
asiniy Avatar answered Sep 09 '25 03:09

asiniy