I am trying to get my head around react portals so I created a portal root for header content in my component called MasterLayout:
<div
ref={portalRoot => {
this.portalRoot = portalRoot;
}}
/>
In this component it throws an error:
TypeError: Cannot read property 'appendChild' of undefined
componentDidMount() {
26 | debugger
> 27 | this.portalRoot.appendChild(this.container);
| ^ 28 | }
Trying to inject content into this portalRoot from another component called FlexStuff:
const PortalContent = (
<SearchWidgetWrapper>
<SearchWidgetContent justify="flex-end" mx="auto">
<SearchContainer>
<Box>portalcontent</Box>
</SearchContainer>
</SearchWidgetContent>
</SearchWidgetWrapper>
);
return [
<Box p={24} flex="1 0 auto" column>
this is FlexStuff
</Box>,
ReactDOM.createPortal(PortalContent, HEADER_CONTAINER),
];
Why do I get this error? How can I inject the FlexStuff content? Link to github
The reason of the error is that the Header component is not rendering children passed via props, so portalRoot
div never gets mounted and the ref stays undefined.
To fix it change the Header component to render the children:
export class Header extends Component {
render() {
return (
<div className="App">
{ this.props.children }
</div>
);
}
}