Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add an alternative method of dynamically loading svg #209

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 34 additions & 2 deletions docs/svg-dynamically-loaded.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
# React SVG Pan Zoom - Getting Started
# React SVG Pan Zoom - Dynamically Loading an SVG


## Using react-svg-pan-zoom-loader
To load an SVG dynamically there's a standalone package (made in collaboration with [nufaylr](https://github.com/nufaylr)).
It's available here https://github.com/nufaylr/react-svg-pan-zoom-loader.

Expand All @@ -14,9 +16,39 @@ const Viewer = () => (
<ReactSVGPanZoom width={500} height={500}>
<svg width={500} height={500} >
{content}
</svg>
</svg>
</ReactSVGPanZoom>
)}/>
)
```

## Using svg-parser and hast-to-hyperscript

If you are having trouble with using react-svg-pan-zoom-loader you may want to try this alternative method using [svg-parser](https://github.com/Rich-Harris/svg-parser) and [hast-to-hyperscript](https://github.com/syntax-tree/hast-to-hyperscript).

See [this CodeSandbox](https://codesandbox.io/s/stoic-voice-pc5jzx) to see it in action.

```js
import {parse as parseSVG} from 'svg-parser'
import {toH} from 'hast-to-hyperscript'

const Viewer = () => {
const [svg, setSVG] = React.useState(<svg />)

React.useEffect(() => {
fetch('file/path/image.svg')
.then((r) => r.text())
.then((text) => {
const hast = parseSVG(text)
const element = toH(React.createElement, hast)
setSVG(element)
})
}, [])

return (
<ReactSVGPanZoom width={500} height={500}>
{svg}
</ReactSVGPanZoom>
)
}
```