javascriptreactjssvg

How to print svg element with base64 format in React?


I upload an svg file as follows:

if (event.target.files && event.target.files[0]) {
  let reader = new FileReader();

  reader.onloadend = upload => {
    let result = upload.target.result // in base64 format  
  };

  reader.readAsDataURL(file);  
}

The result is in base64 format. I am able to show this svg file in the DOM by using the img tag, but I want to use the svg tag.

How can show this svg file in the dom, by using an svg node in React?


Solution

  •     import React from "react";
    import ReactDOM from "react-dom";
    
    const loadSVG = container => {
      var dataURL =
        "data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIj8+Cjxzdmcgdmlld0JveD0iMCAtMTAgMTAwIDg1IiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPgogICAgPGRlZnM+CiAgICAgICAgPGNsaXBQYXRoIGlkPSJjbGlwIj4KICAgICAgICAgICAgPHBhdGggZD0iTTAsMCBMMTAwLDAgTDEwMCw3NSBMMCw3NSBMMCwwCiAgICAgICAgICAgICAgICAgICAgIE01MCwxNSBBMjAsMjAgMCAxLDAgNTAsNjAgQTIwLDIwIDAgMSwwIDUwLDE1CiAgICAgICAgICAgICAgICAgICAgIE01MCwyNSBBMTIuNSwxMi41IDAgMSwxIDUwLDUwIEExMi41LDEyLjUgMCAxLDEgNTAsMjUiLz4KICAgICAgICA8L2NsaXBQYXRoPgogICAgPC9kZWZzPgogICAgPHJlY3QgeD0iMzAiIHk9Ii0xMCIgd2lkdGg9IjQwIiBoZWlnaHQ9IjIwIiByeD0iMTAiIHJ5PSIxMCIvPgogICAgPHJlY3QgeD0iMCIgeT0iMCIgd2lkdGg9IjEwMCIgaGVpZ2h0PSI3NSIgcng9IjE1IiByeT0iMTUiIGNsaXAtcGF0aD0idXJsKCNjbGlwKSIvPgo8L3N2Zz4K";
      var xhr = new XMLHttpRequest();
      xhr.open("GET", dataURL);
      xhr.addEventListener("load", function(ev) {
        var xml = ev.target.response;
        var dom = new DOMParser();
        var svg = dom.parseFromString(xml, "image/svg+xml");
        container.appendChild(svg.rootElement);
      });
      xhr.send(null);
    };
    
    const App = () => {
      React.useEffect(() => {
        loadSVG(refContainer.current);
      }),
        [];
      const refContainer = React.useRef(null);
      return <div ref={refContainer} />;
    };