Search code examples
javascriptreactjssvg-sprite

React and SVG sprite


I am using React, and I am trying to load a svg icon from a sprite. My sprite is like this:

<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
  <defs>
    <symbol viewBox="0 0 28.3 28.3" id="square">
      <path d="M.3 30.7h27L13.8 3.8zM126.3-51.7c-8.8 0-16 7.2-16 16s7.2 16 16 16 16-7.2 16-16-7.2-16-16-16z" />
      <path d="M0 28.3h28.3L14.2 0 0 28.3zm5.3-3.2l8.9-17.7L23 25.1H5.3z" />
    </symbol>
    <symbol viewBox="0 0 28.3 28.3" id="circle">
      <circle cx="14.2" cy="14.2" r="14.2" />
    </symbol>
  </defs>
</svg>

And I load it with:

<svg viewBox="0 0 28.3 28.3" className="App-icon">
    <use xlinkHref="./sprite#square" />
</svg>

With no results. I made a sandbox as an example: https://codesandbox.io/s/l711v6j7v7


Solution

  • If you want to reference it as external resource you need to use the proper URL to the svg file and it needs to be publicly accessible. So in the codesandbox you need to move it to the public folder, so that you can access it in the browser via

    https://codesandbox.io/s/l711v6j7v7/sprite.svg
    

    Then you can reference it like this:

    <use href="/sprite.svg#square" />
    

    See this fork of your codesandbox.