SoFunction
Updated on 2025-04-13

Method of using ResizeObserver to observe changes in element size in React

Method of using ResizeObserver to observe changes in element size in React

Updated: December 25, 2024 10:51:33 Author: The lost little coder Ling Lingfa
Use ResizeObserver in React to observe the size changes of elements. You can encapsulate the logic of ResizeObserver by creating a custom Hook and use this Hook in the component. The following is a complete example, showing how to use ResizeObserver in React to observe the size changes of elements. Friends who need it can refer to it.

Preface

Use ResizeObserver in React to observe changes in size of elements. You can encapsulate the logic of ResizeObserver by creating a custom Hook and use this Hook in your component. Here is a complete example showing how to use ResizeObserver in React to observe changes in size of an element.

Custom Hook

First, create a custom Hook to encapsulate the logic of ResizeObserver:

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

const useResizeObserver = () => {
  const [size, setSize] = useState({ width: 0, height: 0 });
  const elementRef = useRef(null);

  useEffect(() => {
    const resizeObserver = new ResizeObserver(entries => {
      for (let entry of entries) {
        setSize({
          width: ,
          height: 
        });
      }
    });

    if () {
      ();
    }

    return () => {
      if () {
        ();
      }
      ();
    };
  }, []);

  return [elementRef, size];
};

export default useResizeObserver;

explain

  1. useResizeObserver Hook: Create a custom Hook, returning a ref and element size.
  2. useState: Used to store the size of the element.
  3. useRef: Used to reference the element to be observed.
  4. useEffect: Created when component is mountedResizeObserverInstance and clean the observer when component is uninstalled.
  5. : Start observing the changes in the size of the element.
  6. and: Stop observing the size changes of the element and disconnect the observer.

Use custom Hook

Use this custom Hook in the component to observe the size changes of the element:

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

const MyComponent = () => {
  const [elementRef, size] = useResizeObserver();

  return (
    <div>
      <div ref={elementRef} style={{ width: '50%', height: '200px', backgroundColor: 'lightblue' }}>
        Resize me!
      </div>
      <p>Width: {}px</p>
      <p>Height: {}px</p>
    </div>
  );
};

export default MyComponent;

explain

  • useResizeObserver Hook: Call a custom Hook in the component to get the size of the ref and element.
  • ref attribute: Assign ref to the element to be observed.
  • Show the size of the element: Displays the width and height of the element in the component.

The above is the detailed content of the method of using ResizeObserver to observe changes in element size. For more information about the observation changes in React ResizeObserver, please pay attention to my other related articles!

  • React
  • ResizeObserver
  • size
  • change

Related Articles

  • react koa rematch How to create a server-side rendering shelf

    This article mainly introduces how react koa rematch creates a set of server-side rendering shelves. The article introduces the sample code in detail, which has certain reference learning value for everyone's learning or work. Friends who need it, please learn with the editor below.
    2019-06-06
  • Teach you to use vscode to build a react-native development environment

    This article records how to use vscode to create a modern react-native development environment, aiming to improve development efficiency and quality. This article will share with you the problems and solutions I encountered. Interested friends will follow the editor to take a look.
    2021-07-07
  • How to export Excel on the front end

    This article mainly introduces the detailed explanation of the front-end export Excel method. Friends in need can refer to it for reference. I hope it can be helpful. I wish you more progress and get a promotion as soon as possible.
    2022-07-07
  • 2022 latest front-end common react interview questions collection

    This article mainly introduces a collection of common front-end react interview questions, introduces the introduction of React Fiber and fetch packaging code. This article introduces you very detailedly. Friends who need it can refer to it.
    2022-09-09
  • Brief analysis of React Native startReactApplication method

    This article mainly introduces a brief analysis of the React Native startReactApplication method. This article introduces you very detailedly and has certain reference value for your study or work. Friends who need it can refer to it.
    2021-09-09
  • Understand several ways of communicating between React Native modules and JS modules

    This article mainly introduces several ways to deeply understand React Native native modules and JS modules. It has certain reference value. If you are interested, you can learn about it.
    2017-07-07
  • Example of method to implement react server-side rendering

    This article mainly introduces examples of methods to implement react server-side rendering. The editor thinks it is quite good. I will share it with you now and give you a reference. Let's take a look with the editor
    2019-01-01
  • Detailed explanation of React's callback rendering mode

    This article mainly introduces the detailed explanation of React's callback rendering mode. The example code is introduced in this article in detail, which has a certain reference learning value for everyone's study or work. Friends who need it, please learn with the editor below.
    2020-09-09
  • Detailed explanation of parent-child component communication in React

    This article mainly introduces a detailed explanation of the communication between parent and child components in React. In the parent component, adding attribute data to the child component can realize the communication between parent components. The article has a certain reference value by introducing the detailed content around the topic. If you need it, you can refer to it.
    2022-08-08
  • Detailed explanation of the use of Refs, three major properties of React

    This article mainly introduces the detailed explanation of the use of React, the three major properties of React, to help everyone better understand and learn to use React. Interested friends can learn about it.
    2021-04-04

Latest Comments