Skip to content

Commit

Permalink
Add an alternative method of dynamically loading svg
Browse files Browse the repository at this point in the history
  • Loading branch information
kasbah committed May 8, 2022
1 parent afb0106 commit aaee908
Showing 1 changed file with 32 additions and 2 deletions.
34 changes: 32 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,37 @@ 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).

```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>
)
}
```

0 comments on commit aaee908

Please sign in to comment.