0

Some reason i need use a react project in Rails html like this:

<html>
  ...
  <script src="<react_project_bundle_file>.js"></script>
</html>

Because a lot of SVG images are used by icon in this react project, i'm tried refactor with svg-sprite-loader & svgo-loader. It's working very well when visit this page first visit, but the second time visited the page, none of these SvgIcon appear.

// svg-icon.jsx
import '../icons';

const SvgIcon = props => (
    <svg>
        <use xlinkHref={`#icon--${props.icon}`} />
    </svg>
);
// icons/index.js

const requireAll = requireContext => requireContext.keys().forEach(requireContext);
// `icons/svg` is a subdirectory to store all SVG files
const req = require.context('./svg', false, /\.svg$/);
requireAll(req);

And svg inline in the bundle js file:

"use strict";
...

var symbol = new _node_modules_svg_baker_runtime_browser_symbol_js__WEBPACK_IMPORTED_MODULE_0___default.a({
  "id": "icon--file-upload",
  "use": "icon--file-upload-usage",
  "viewBox": "0 0 20 20",
  "content": "<symbol xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 20 20\" id=\"icon--file-upload\"><path d=\"M5.917 6.886L9.64 3.165a.54.54 0 01.777 0l3.721 3.721c.355.355.096.94-.395.94h-1.854L10.784 12.2a.798.798 0 01-.968.573.78.78 0 01-.586-.573L8.126 7.825H6.313c-.491 0-.75-.584-.396-.939zM17 11.602v2.249A3.147 3.147 0 0113.865 17H6.149A3.15 3.15 0 013 13.851v-2.25c0-.572.463-1.022 1.022-1.022.56 0 1.023.45 1.023 1.023v2.249c0 .6.49 1.104 1.104 1.104h7.716c.6 0 1.09-.504 1.09-1.104v-2.25c0-.572.464-1.022 1.023-1.022.572 0 1.022.45 1.022 1.023z\" fill=\"#FFF\" fill-rule=\"evenodd\" /></symbol>"
});

...

HTML element debug

  • First visit

    <svg>
      <use xlink:href="#icon--upload">
        #shadow-root(closed)
        <svg xmlns="http://www.w3.org/2000/svg" ...>
          <path ...>
        </svg>
      </use>
    </svg>
    
  • Second visit:

    <svg>
      <use xlink:href="#icon--upload">
        #shadow-root(closed)
        !!! not anything !!!
      </use>
    </svg>
    

What's the problem here? Why is it correct the first time and not the second time?

yi quo
  • 3
  • 1
  • 5

1 Answers1

0

Svg sprite not include!

fetch('svg-sprite.svg')
  .then(res => res.text())
  .then(data => {
    document.getElementById('svg-sprite').innerHTML = data;
  });

UPDATE:

svg-sprite.svg not found! worked by added path to <use xlinkHref={`static/svg-sprite.svg#icon--${icon}`} /> in the <svg></svg>

yi quo
  • 3
  • 1
  • 5