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:

then:

  1. import the sprite using whatever your regular React-component-ification system looks like,
  2. render it on the page someplace with display: 'none';,
  3. change your href="/path/to/sprite.svg#my-cool-icon" to href="#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!

#webdev #frontend

from @ellotheth@bsd.network