cacheElements {boolean} ▶︎ false
Reuse the converted React element across mounts of the same SVG instead of parsing it every time. Use it for SVGs that mount often, like icons in virtualized lists. With uniquifyIDs, only instances that have a uniqueHash when they mount are cached.
The cache is shared by all instances (independent of the CacheProvider) and holds the 100 most recently used elements. Call clearElementCache() (exported from react-inlinesvg) to empty it, for example between tests.
cacheRequests {boolean} ▶︎ true
Cache remote SVGs in memory. When used with the CacheProvider, requests are also persisted in the browser cache.
description {string}
A description for your SVG. It will override an existing <desc> tag.
fetchOptions {RequestInit}
Custom options for the request.
innerRef {React.Ref<SVGElement | null>}
Set a ref on the SVG element.
The SVG is processed and parsed so the ref won't be set on the initial render.
You can use the onLoad callback to get and use the ref instead.
loader {node}
A component to be shown while the SVG is loading.
onError {function}
A callback to be invoked if loading the SVG fails.
This will receive a single argument with:
Any browser that supports inlining SVGs and fetch will work.
If you need to support legacy browsers, include a polyfill for fetch in your app.
CORS
If you are loading remote SVGs, you must ensure they have CORS headers.
Why do you need this package?
One reason SVGs are awesome is that you can style them with CSS.
Unfortunately, this is not useful in practice because the style element has to be in the same document. This leaves you with three bad options:
Embed the CSS in the SVG document
Can't use your CSS preprocessors (LESS, SASS)
Can't target parent elements (button hover, etc.)
Makes maintenance difficult
Link to a CSS file in your SVG document
Sharing styles with your HTML means duplicating paths across your project, making maintenance a pain
Not sharing styles with your HTML means extra HTTP requests (and likely duplicating paths between different SVGs)
Still can't target parent elements
Your SVG becomes coupled to your external stylesheet, complicating reuse.
Embed the SVG in your HTML
Bloats your HTML
SVGs can't be cached by browsers between pages.
A maintenance nightmare
But there's an alternative that sidesteps these issues: load the SVG with a GET request and then embed it in the document. This is what this component does.
Note
The SVG <use> element can be used to achieve something similar to this component. See this article for more information and this table for browser support and caveats.
Credits
Thanks to @matthewwithanm for creating this component and so kindly transferring it to me.
I'll definitely keep up the good work! ❤️