README
@cutting/use-parent - reusable react hooks for reusable things
install
yarn add @cutting/use-parentsize-svg
# or
npm install @cutting/use-parentsize-svg
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 optionalnumber
that will throttle the speed at which reize events are raised to the calling code.initialValues
- initially, theref
will benull
and nowidth
orheight
values can be returned until it is mounted. TheinitialValues
option can return a specificwidth
andheight
value until theref
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 parenttransformFunc: ({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-parentsize-svg';
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>
);
};