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
- Host: GitHub
- URL: https://github.com/devgru/react-svg-guides
- Owner: devgru
- Created: 2024-10-31T00:34:36.000Z (over 1 year ago)
- Default Branch: main
- Last Pushed: 2025-02-23T19:03:34.000Z (over 1 year ago)
- Last Synced: 2025-02-23T20:19:08.076Z (over 1 year ago)
- Language: TypeScript
- Homepage:
- Size: 41 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
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;
}
```