useDimension documentation

The useDimension hook is a custom hook for tracking the dimensions of an HTML element. It returns an object containing the dimensions and related properties of the tracked element.

Type

Hooks

import

import { useDimension } from '@pillar-ui/hooks'

Why useDimension

The useDimension hook simplifies the process of tracking the size of an HTML element. It uses the ResizeObserver API to monitor changes in the dimensions of an element and provides an easy-to-use function for retrieving these dimensions.

Installation

To use the useDimension hook, simply import it into your React component:

// With NPM
npm install --dev '@pillar-ui/hooks'

// With YARN
yarn add '@pillar-ui/hooks'

// Uses
import { useDimension } from '@pillar-ui/hooks'

Parameters

  • elementRef: The RefObject that points to the HTML element you want to track.

Returned Values

The useDimension hook returns an object with the following properties:

  • width: The width of the HTML element.
  • height: The height of the HTML element.
  • padding: An object containing the padding (in pixels) for each side of the HTML element.
  • margin: An object containing the margin (in pixels) for each side of the HTML element.
  • border: An object containing the border width (in pixels) for each side of the HTML element.
  • content: An object indicating the width and height of the content part of the HTML element.

Usage

To use the useDimension hook, call it inside your functional component like so:

import { useRef } from 'react'
import { useDimension } from '@pillar-ui/hooks' // Adjust the path accordingly

function MyComponent() {
  const ref = useRef<HTMLElement>(null)
  const dimension = useDimension(ref)

  return <div ref={ref}>Measure me!</div>
}

In the example above, the useDimension is used to track the dimensions of an HTML element with the "Measure me!" text. A reference to this element is created using the useRef hook, which is then passed as a parameter to the useDimension hook.

Implementation details

The useDimension hook uses the browser's ResizeObserver API to track changes in the size of an HTML element. It then parses this data into an easy-to-use object, which includes fields for the width, height, padding, margin, border, and content of the element.

TypeScript Support

The useDimension hook is written in TypeScript and provides type definitions for its parameters and return values.

Troubleshooting

If you encounter issues with the useDimension hook, ensure that your browser supports the ResizeObserver API and that your code is executing on the client-side.

Conclusion

The useDimension hook provides a simple and effective way to track changes in an HTML element's size. By handling the complex work of interacting with the ResizeObserver API, this hook allows you to focus on the more important parts of your application.