~/notes/inline-svg-ids-collide

The same inline SVG twice means duplicate ids

Gradients, paths for animateMotion and patterns are looked up by id in the whole document. Render the same SVG twice and the second copy points at the first.

· 1 min read · written in English

Inline SVGs share one id namespace with the page. If a component renders the same SVG in two places, url(#sky) and <mpath href="#route"/> in the second copy resolve to the first element with that id. If the first copy is hidden or removed, the second one breaks.

Fix: suffix every id per render, and rewrite the references with it:

ts
let uid = 0;
function uniqueIds(svg: string) {
  const n = ++uid;
  return svg
    .replace(/id="([\w-]+)"/g, `id="$1-${n}"`)
    .replace(/(href="#|url\(#)([\w-]+)/g, `$1$2-${n}`);
}