@cutting/use-get-parent-size

Sizes an SVG document to the containing parent using the resize-observer.

Usage no npm install needed!

<script type="module">
  import cuttingUseGetParentSize from 'https://cdn.skypack.dev/@cutting/use-get-parent-size';
</script>

README

@cutting/use-parent - reusable react hooks for reusable things

npm version code style: prettier

install

pnpm add @cutting/use-get-parent-size

# or

npm install @cutting/use-get-parent-size

useParentSize

A React hook that allows you to use a ResizeObserver to measure an element's size.

usage

const { width, height } = useParentSize(ref, options);

useParentSize takes a react ref object and an optional options object.

Options

export interface UseParentSizeOptions {
  debounceDelay: number;
  initialValues: Dimensions; // { width, height }
  transformFunc?: ({ width, height }: Dimensions) => Dimensions;  // default (x) => x
}
  • debounceDelay - an optional number that will throttle the speed at which reize events are raised to the calling code.

  • initialValues - initially, the ref will be null and no width or height values can be returned until it is mounted. The initialValues option can return a specific width and height value until the ref actually references a valid DOM node. e.g. const { width, height } = useParentSize(ref, { width: 100, height: 50});

    Default is { width: 1, height: 1}

  • transformFunc optional function to transform the results, e.g. to halve the size of the parent

    transformFunc: ({width, height}) => ({width: width / 2, height: height /2})
    

    Default is identity, (x) => x

import type { FC } from 'react';
import { useRef } from 'react';
import type { UseParentSizeOptions } from '@cutting/use-get-parent-size';

export const ResponsiveSVG: FC = ({
  children
}) => {
  const ref = useRef<HTMLDivElement>(null);
  const { width, height } = useParentSize(ref, options);
  const aspect = width / height;

  const adjustedHeight = Math.ceil(width / aspect);

  return (
    <div ref={ref}>
      <svg
        viewBox={`${origin.x} ${origin.y} ${width} ${adjustedHeight}`}
      >
        {children}
      </svg>
    </div>
  );
};