Capítulo 17 de 988

Chapter 17: Measuring DOM nodes

Core Idea

If you want to measure a DOM node, you can assign a React Ref to it and then use the getBoundingClientRect() browser API to get the position and size of the node.

Key Concepts

  • Measure using the useCurrentScale() hook
  • Versions prior to v4.0.110
  • Example project
  • Versions prior to v4.0.103
  • See also

Code Examples

export const MyComponent = () => {
  const ref = useRef<HTMLDivElement>(null);

  const [dimensions, setDimensions] = useState<{
    correctedHeight: number;
    correctedWidth: number;
  } | null>(null);

  const scale = useCurrentScale();

  useEffect(() => {
    if (!ref.current) {
      return;
    }

    const rect = ref.current.getBoundingClientRect();

    setDimensions({
      correctedHeight: rect.height / scale,
      correctedWidth: rect.width / scale,
    });
  }, [scale]);

  return (
    <div>
      <div ref={ref}>Hello World!</div>
    </div>
  );
};
  • What it demonstrates: Usage pattern for Measuring DOM nodes from the official docs.

Key Takeaways

  1. Understand measure using the usecurrentscale() hook when working with Measuring DOM nodes.
  2. Understand versions prior to v4.0.110 when working with Measuring DOM nodes.
  3. Understand example project when working with Measuring DOM nodes.
  4. Understand versions prior to v4.0.103 when working with Measuring DOM nodes.
  5. Understand see also when working with Measuring DOM nodes.

Connects To

  • Absolute Fill: related page in the Fundamentals & Core Concepts section.
  • Animating Properties: related page in the Fundamentals & Core Concepts section.
  • Animation Math: related page in the Fundamentals & Core Concepts section.