buttery-components-logo
buttery.tools

useDynamicNode

A hook that returns controls for dynamically creating a node at in the <body /> node of the DOM.

This hook is perfect for creating arbitrary divs in the body to attach React Portals to.

Usages

The useDynamicNode is a utility hook to separate out the logic of node creation from portal management. In order to promote the most accessible experience, Portals should be attached to nodes at the root of the document, or in this case the body node. In order to create the best developer experience, this hook replaces the need to statically add and manage div's with specific IDs in order to attach portals.

The hook creates a div with a random GUID and then adds it as the child of the body node in the DOM. The example is designed to display how easy it is to manage accessible portals using the createPortal API from React.

The state of the hook manages when to use the destroyNode function.

Remember to always use the destroyNode funciton returned by the hook to destroy the reference to the the node and remove it from the DOM. Otherwise the node won't be released from memory to be garbage collected and the node will just persist at the root.

Styling

Examples

API

useDynamicNode