SVG created using EncodeURI doesn't work with 2 hex colors on React-leaflet

Viewed 26

Working with React-Leaflet, I'm trying to provide a custom icon to a Marker made with URI encoded SVG. When providing an Hex color once, all works well.

var stopCircleSvg = 
  '<svg xmlns="http://www.w3.org/2000/svg" width="67" height="67">'+
  '<g>' +
    '<circle id="1" cx="34" cy="34" r="3" stroke="#D7629B" stroke-width="1.5" fill="none"/>' +
    '<circle id="2" cx="34" cy="34" r="1" fill="red" />' +
  '</g>' + 
'</svg>';

var url = encodeURI("data:image/svg+xml," + stopCircleSvg).replace("#", "%23");
  var CustomIcon = Icon.extend({
    options: {
      iconSize: [stopCircleSize, stopCircleSize],
      iconAnchor: [stopCircleSize / 2, stopCircleSize / 2],
    },
  });
....
  icon={
    new CustomIcon({ iconUrl: url })
  }

Work well with regular color and hex color

When providing an Hex color to more elements, the SVG breaks.

var stopCircleSvg = 
  '<svg xmlns="http://www.w3.org/2000/svg" width="67" height="67">'+
  '<g>' +
    '<circle id="1" cx="34" cy="34" r="3" stroke="#D7629B" stroke-width="1.5" fill="none"/>' +
    '<circle id="2" cx="34" cy="34" r="1" fill="#D7629B" />' +
  '</g>' + 
'</svg>';
var url = encodeURI("data:image/svg+xml," + stopCircleSvg).replace("#", "%23");

SVG breaks

1 Answers

you should call encodeURIComponent rather than encodeURI and then you won't need the replace call at all.

var stopCircleSvg = 
  '<svg xmlns="http://www.w3.org/2000/svg" width="67" height="67">'+
  '<g>' +
    '<circle id="1" cx="34" cy="34" r="3" stroke="#D7629B" stroke-width="1.5" fill="none"/>' +
    '<circle id="2" cx="34" cy="34" r="1" fill="#D7629B" />' +
  '</g>' + 
'</svg>';

var url = "data:image/svg+xml," + encodeURIComponent(stopCircleSvg);

document.getElementById("i").setAttribute("src", url);
img {
  transform: scale(4);
}
<img id="i">

Related