import React, { useEffect, useRef, useState } from "react"; /** * An SVG element with an optional background color that * automatically sizes itself to its contents. */ export const AutoSizingSvg = React.forwardRef( ( props: { padding: number; bgColor?: string; children: JSX.Element | JSX.Element[]; }, ref: React.ForwardedRef ) => { const { bgColor, padding } = props; const [x, setX] = useState(0); const [y, setY] = useState(0); const [width, setWidth] = useState(1); const [height, setHeight] = useState(1); const gRef = useRef(null); useEffect(() => { const svgEl = gRef.current; if (svgEl) { const bbox = svgEl.getBBox(); setX(bbox.x - padding); setY(bbox.y - padding); setWidth(bbox.width + padding * 2); setHeight(bbox.height + padding * 2); } }); return ( {bgColor && ( )} {props.children} ); } );