Home  >  Article  >  Web Front-end  >  Custom React Hook: useResizeObserver

Custom React Hook: useResizeObserver

王林
王林Original
2024-08-02 10:03:11612browse

Custom React Hook: useResizeObserver

In this post, I'll share a custom React hook called useResizeObserver. This hook helps you observe and get the bounding client rect of a DOM element, updating the rect whenever the element is resized. It's part of my React library, react-helper-hooks, which contains many useful hooks to save developers time.

Source Code

import { useEffect, useRef, useState } from 'react';

type ObserverRect = Omit<DOMRectReadOnly, 'toJSON'>;

export default function useResizeObserver(): Array<any> {
  const ref = useRef<any>(null);
  const [rect, setRect] = useState<ObserverRect>();

  useEffect(() => {
    const observer = new ResizeObserver(() => {
      if (ref.current) {
        const boundingRect = ref.current.getBoundingClientRect();
        setRect(boundingRect);
      }
    });
    observer.observe(ref.current);

    return () => observer.disconnect();
  }, [ref]);

  return [ref, rect];
}

How It Works

The useResizeObserver hook leverages the ResizeObserver API to track size changes of a DOM element. It returns a ref to be attached to the target element and the current bounding client rect of that element.

Example Usage

Here's an example of how to use the useResizeObserver hook in a functional component:

import React from 'react';
import useResizeObserver from './useResizeObserver';

function ExampleComponent() {
  const [ref, rect] = useResizeObserver();

  return (
    <>
       <textarea ref={ref} style={{ resize: 'both', height: 100, width: 300 }}>
           Resize this element to see the changes:
       </textarea>

      {rect && (
        <div>
          <p>Top: {rect.top}</p>
          <p>Left: {rect.left}</p>
          <p>Width: {rect.width}</p>
          <p>Height: {rect.height}</p>
        </div>
      )}
    </>
  );
}

export default ExampleComponent;

In this example, a textarea element is made resizable. The useResizeObserver hook tracks its dimensions, which are displayed outside the textarea.

About react-helper-hooks

The useResizeObserver hook is part of my React library, react-helper-hooks. This library includes a collection of custom hooks designed to save developers time and effort. Hooks like useResizeObserver provide reusable, efficient solutions for common tasks in React applications.

Feel free to check out the library and contribute or suggest new hooks!


Let me know if you need any changes or additional information!


Follow me on X ( Twitter ) - https://twitter.com/punitsonime
Let's connect on linked in - https://www.linkedin.com/in/punitsonime/

The above is the detailed content of Custom React Hook: useResizeObserver. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn