Documentation
useRect

useRect

The useRect hook provides a simple way to track and update the position and dimensions of a DOM element in relation to the viewport or a specified container. It can be particularly useful for tasks like positioning popups, tooltips, or tracking element visibility.

Usage

First, you need to import the useRect hook from the kitchn package.

import { useRect } from "kitchn";

Example

Here is an example of how to use the useRect hook in a component:

Parameters

The useRect hook accepts the following parameters:

NameTypeDescription
initialStateReactiveDomReact | () => ReactiveDomReact(Optional) Initial state for the rectangle dimensions and position.

ReactiveDomReact

NameTypeDescription
topnumberThe top position of the element relative to the container or viewport.
leftnumberThe left position of the element relative to the container or viewport.
rightnumberThe right position of the element relative to the container or viewport.
bottomnumberThe bottom position of the element relative to the container or viewport.
widthnumberThe width of the element.
heightnumberThe height of the element.
elementTopnumberThe top position of the element relative to the container or viewport, including any scrolling.

Return Value

The useRect hook returns an object with the following properties and functions:

NameTypeDescription
rectReactiveDomReactThe current position and dimensions of the tracked element.
setRect(event: React.MouseEvent<HTMLElement> | React.FocusEvent<HTMLElement>, getContainer?: () => HTMLElement or null)A function to update the position and dimensions of the tracked element.
setRectWithRef(React.MutableRefObject<HTMLElement | null>, getContainer?: () => HTMLElement or null)A function to update the position and dimensions of the tracked element using a ref.