useToggleLayer

import { useToggleLayer } from 'react-laag';

Hook variant of <ToggleLayer /> that tries to achieve the same thing: rendering layers. When using <ToggleLayer />, the layer is coupled tightly to the trigger element, but there are cases where the trigger element is unknown beforehand, or there simply isn't a trigger-element (but another source to tie the layer to). In such cases it is recommended to use useToggleLayer().

Common use cases: context-menus, text-selection.

Type
(
  renderLayer: (props: RenderLayerProps): ReactNode,
  options: Options
): [ReactNode, ToggleLayerProps]
RenderLayerProps
details

See <ToggleLayer/>'s renderLayer prop for more info.

Options
details

Same props as <ToggleLayer/>, except for isOpen, onOutsideClick() and onDisappear().

ToggleLayerProps
details
isOpen
boolean

Describes whether the layer is open or closed

open
(props: {clientRect: ClientRect | (): ClientRect, target: HTMLElement})

Shows the layer.
The clientRect prop is used to position the layer. Provide a function returning a ClientRect if you want react-laag to re-position the layer on scrolling / resizing.
The target prop is used to determine where to place the layer in the DOM.

openFromMouseEvent
(event: MouseEvent): void

Utility method that shows the layer with a mouse event as its source.

openFromRef
(ref: React.RefObject): void

Utility method that shows the layer with a ref (containing a reference to a HTMLElement) as its source.

openFromContextMenuEvent
(event: MouseEvent): void

Utility method that shows the layer with a context-menu-event as its source.

close
(): void

Hides the layer

layerSide
LayerSide | null

null when the layer is closed.
When the layer is open, layerSide describes on which side the layer is currently positioned relative to the trigger. When layerSide is "center", it means that the layer is anchored "CENTER".
LayerSide = "top" | "right" | "bottom" | "left" | "center"

Example

function HookExample() {
  const [element, toggleLayerProps] = useToggleLayer(
    // determine how to render the layer
    ({ isOpen, layerProps }) => isOpen && <div {...layerProps} />,
    // optionally provide options
    {
      placement: {
        anchor: "BOTTOM_CENTER",
        autoAdjust: true,
        snapToAnchor: true,
        triggerOffset: 12,
        scrollOffset: 16,
        possibleAnchors: [
          "BOTTOM_CENTER",
          "LEFT_CENTER",
          "RIGHT_CENTER",
          "TOP_CENTER"
        ]
      },
      closeOnOutsideClick: true
    }
  );

  // react to events
  return (
    <>
      {element}
      <div onContextMenu={toggleLayerProps.openFromContextMenuEvent}></div>
    </>
  );
}