From 650158ca3598f3c713c7bd330ecde629c6ad20c6 Mon Sep 17 00:00:00 2001 From: Michel Weststrate Date: Thu, 1 Oct 2020 05:32:07 -0700 Subject: [PATCH] Introduce renderReactRoot utility Summary: This is a small utility to be able to render a react element without giving it a position somewhere in the react render tree, so that dialogs can be triggered and rendered imperatively for example. Reviewed By: cekkaewnumchai Differential Revision: D24021752 fbshipit-source-id: 84633624c63c72a38a1b277207efba75af358a03 --- desktop/app/src/utils/renderReactRoot.tsx | 27 +++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 desktop/app/src/utils/renderReactRoot.tsx diff --git a/desktop/app/src/utils/renderReactRoot.tsx b/desktop/app/src/utils/renderReactRoot.tsx new file mode 100644 index 000000000..09699d2d1 --- /dev/null +++ b/desktop/app/src/utils/renderReactRoot.tsx @@ -0,0 +1,27 @@ +/** + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @format + */ + +import {render, unmountComponentAtNode} from 'react-dom'; + +/** + * This utility creates a fresh react render hook, which is great to render elements imperatively, like opening dialogs. + * Make sure to call `unmount` to cleanup after the rendering becomes irrelevant + */ +export function renderReactRoot( + handler: (unmount: () => void) => React.ReactElement, +): void { + const div = document.body.appendChild(document.createElement('div')); + render( + handler(() => { + unmountComponentAtNode(div); + div.remove(); + }), + div, + ); +}