Why react elements do not rerender again after removing them from the DOM

245 Views Asked by At

I was working with portals in React.

Take a look at these code snippets.

// Layout.js
function DashboardLayout() {
    const [state, setState] = useState(0);

    console.log("Component rerendered");

    return (
        <>
            <button
                onClick={() => {
                    setState(state + 1);
                }}
            >
                change state
            </button>
            <div className="app-content content">
                <div className="content-wrapper">
                    <div className="content-header row"></div>
                </div>
            </div>
            <LoginModal />
        </>
    );
}

// LoginModal
function LoginModal() {
    return ReactDOM.createPortal(
        <>
            <div
                className="modal fade text-left show">
                <div className="modal-dialog modal-dialog-centered  modal-md">
                    <div className="modal-content">
                        <div className="modal-body">
                            <h1>something</h1>
                        </div>
                    </div>
                </div>
            </div>
        </>,
        document.querySelector("#overlays")
    );
}

Everything works well, the modal will be shown correctly. the problem comes up when I remove the modal element manually from the browser inspector. When change state button is clicked that should cause a rerender and the modal which was removed should be rendered again, but actually that part doesn't rerender. What's wrong?

1

There are 1 best solutions below

0
On

It's correct behavior. If you want them to appear on the page after the user deleted them, some extra work should be done. It probably involves setInterval and checking that the modal element is still there, then setting it in DOM.

It's not a trivial React usage but quite possible.