to inline a sprite svg that was externally linked
This whole experience seemed painfully obvious in retrospect and I felt a bit dumb, so on the off-chance I'm not the only one in this position, let me save you some time.
If you are:
- working in #ReactJS,
- using a library like svgr to turn your #SVG icons into React components, and
- trying to avoid the cache-busting hassle for an externally linked (
xlinkHref
orhref
) sprite that's not in your nice react-ified SVG system yet
then:
- import the sprite using whatever your regular React-component-ification system looks like,
- render it on the page someplace with
display: 'none';
, - change your
href="/path/to/sprite.svg#my-cool-icon"
tohref="#my-cool-icon
“
and that's it.
In my case, I took something more or less like this:
import { render } from 'react-dom';
const SpriteIcon = ({ name }) => <svg>
<use href={`/img/icons/sprite.svg#${name}`} />
</svg>;
const App = () => <div>
<SpriteIcon name="my-cool-icon" />
</div>;
render(<App />, document.querySelector('#app'));
and turned it into this, roughly:
import { render } from 'react-dom';
// @svgr/webpack lets me do this nicely
import SpriteSource from 'Images/icons/sprite.svg';
// set up the invisible container for the whole sprite
// <span /> or <div /> or whatever would also work probably
const Sprite = () => <svg style={{display: 'none'}}>
<SpriteSource />
</svg>;
// the container for the individual icons just needs the anchor
const SpriteIcon = ({ name }) => <svg>
<use href={`#${name}`} />
</svg>;
// render both
const App = () => <div>
<Sprite />
<SpriteIcon name="my-cool-icon" />
</div>;
render(<App />, document.querySelector('#app'));
Another yak down!