preactjs / preact-compat

ATTENTION: The React compatibility layer for Preact has moved to the main preact repo.
http://npm.im/preact-compat
MIT License
950 stars 148 forks source link

Bug: Portals aren't unmounting #501

Open edygarOliveira opened 5 years ago

edygarOliveira commented 5 years ago

Problem

Portals (#486) are never unmounted. https://codesandbox.io/s/wk6y1j8777

Expected Behavior

They should clear the target once they are unmounted. https://codesandbox.io/s/9znym0r8yp

Possible solution

Instead of a Functional Component, a regular class component calling unmountComponentAtNode on componentWillUnmount could solve it.

dbergey commented 5 years ago

Including this file:

import { createElement as h } from 'react';
import { unmountComponentAtNode, unstable_renderSubtreeIntoContainer as renderSubtreeIntoContainer } from 'react-dom';

class Portal {
    componentWillUnmount() {
        unmountComponentAtNode(this.props.container);
    }
    componentDidMount() {
        renderSubtreeIntoContainer(this, this.props.vnode, this.props.container);
    }
    render() {
        // render nothing at original location
    }
}

export function createPortal(vnode, container) {
    return h(Portal, { vnode, container });
}

and using the exported createPortal instead of the one in preact-compat solved it for me (as suggested in the 'possible solution' above).