Skip to main content

useSVGViewBox

Hook used to generate and manipulate value for the viewBox property of an <svg /> element.

You are not required to use this hooks for your <svg /> element. However, this hooks can help you to maintain the viewBox property, so you do no need to hardcode it yourself.

Configuration

useSVGViewBox accepts 2 arguments:

PropertyTypeDefaultDescription
primitivesPrimitivesLikerequiredPrimitive(s) inside the viewBox.
viewBoxOptionsComputeSVGViewBoxOptions{}Options to construct the viewBox (optional).

(PrimitivesLike) primitives

Type Declaration: Primitive | { boundingBox: BoundingBox } | (Primitive | { boundingBox: BoundingBox })[] (required)

It can be a primitive or an object with boundingBox property, or an array of them.

Example:

const circle = useCircle();
const { boundingBox } = useSquare();

const primitivesLike = circle;
// or
const primitivesLike = { boundingBox };
// or an array of primitives like
const primitivesLike = [circle, { boundingBox }];

(ComputeSVGViewBoxOptions) viewBoxOptions

PropertyTypeDefaultDescription
paddingnumber
| { x?: number; y?: number }
| { top?: number; left?: number; right?: number; bottom?: number }
undefinedPadding of the view box around the SVG path(s).
xnumberundefinedOrigin x value of the view box.
ynumberundefinedOrigin y value of the view box.
widthnumberundefinedWidth of the view box.
heightnumberundefinedHeight of the view box.

Custom configurations to manipulate the view box using padding. By default, if none of the properties are given, the viewBox will be exactly the same from boundingBox.

tip

When you using stroke and strokeWidth properties in <path /> element, you may notice that the stroke is being trimmed. You can set a padding so the the path looked nice in the centre.

If multiple primitives are given, useSVGViewBox will merge all them in the plane, and compute one viewBox to accommodate all of them.

note

If all x, y, width, and height are given, then useSVGViewBox will generate viewBox based on that instead.

But that will require all four of them are given. If one of them is incomplete, they all be ignored.

Example:

const viewBoxOptions = { padding: 50 };
// or using vertical or horizontal padding
const viewBoxOptions = { padding: { x: 20, y: 30 } };
// or directional padding
const viewBoxOptions = { padding: { top: 30, right: 20 } };
// or hardcoding view box
const viewBoxOptions = { x: -100, y: -100, width: 200, height: 200 };

Returns

(string) A string representation of viewBox property for <svg /> element.

Example

import { useCircle, useSVGViewBox } from "react-use-polygon";

function Example() {
const { svgPath, boundingBox } = useCircle();
const viewBox = useSVGViewBox(
{ boundingBox },
{ padding: { x: 100, y: 50 } }
);

return (
<svg viewBox={viewBox}>
<path d={svgPath} />
</svg>
);
}

CommonJS Helper function

computeSVGViewBox is the equivalent helper function for CommonJS, which accepts the same parameters.