An open API service indexing awesome lists of open source software.

https://github.com/devgru/react-svg-guides

⋕ React hooks and components exporting rendered SVG elements' positions
https://github.com/devgru/react-svg-guides

Last synced: over 1 year ago
JSON representation

⋕ React hooks and components exporting rendered SVG elements' positions

Awesome Lists containing this project

README

          

# react-svg-guides

> While HTML supports a variety of layout techniques, SVG is more limited in this regard.
>
> The library provides a set of React hooks and components to capture SVG elements' measurements and expose them via refs, enabling complex SVG-based layouts building.

Explore `demos` package for a glimpse of what this library can help with.

## Usage

### Size measurement

1. Use `useRefWithSize` hook to track element's width and height:

```typescript jsx
import { useRefWithSize } from 'react-svg-guides';

const circleRef = useRefWithSize();
return (



);
```

2. To combine `svg` and `html` elements, use `HTML` component. It renders as a `div` within a `foreignObject`, the `ref` is attached to the `div`:

```typescript jsx
import { HTML, useRefWithSize } from 'react-svg-guides';

const divRef = useRefWithSize();
return (


foreignObject inside SVG


);
```

### Position measurement

1. Use `useRefWithBox` hook to track both element's size and position:

```typescript jsx
import { useRefWithBox } from 'react-svg-guides';

const circleRef = useRefWithBox();
return (



);
```

2. Optionally use `SVG` component to switch the origin point for boxes, from the page's origin to the `SVG` element's origin:

```typescript jsx
import { SVG, HTML, useRefWithBox } from 'react-svg-guides';

const divRef = useRefWithBox();

return (


foreignObject inside SVG


);
```

## Types

```typescript
type RefObjectWithSize = RefObject & {
width: number;
height: number;
};

type RefObjectWithBox = RefObjectWithSize & {
left: number;
horizontalCenter: number;
right: number;
top: number;
verticalCenter: number;
bottom: number;
};

interface HtmlProps extends SVGAttributes {
ref?: RefObject;
}

interface SvgProps extends SVGAttributes {
ref: RefObject;
}

```