Home > database >  How to add color to a path element in an svg dynamically with d3 and react
How to add color to a path element in an svg dynamically with d3 and react

Time:08-13

I have an SVG icon:

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
  <circle cx="12" cy="12" r="12" />
  <path 
    d="M12,2A10,10,0,1,0,22,12,10,10,0,0,0,12,2Zm1,3.3,1.35-1a8,8,0,0,1,4.38,3.34L18.34,9,17,9.49,13,6.7Zm-3.35-1L11,5.3V6.7L7,9.49,5.66,9,5.27,7.69A8.1,8.1,0,0,1,9.65,4.35ZM7.08,17.11l-1.14.1A7.94,7.94,0,0,1,4,12c0-.12,0-.23,0-.35l1-.73,1.38.48,1.46,4.34Zm7.42,2.48a7.83,7.83,0,0,1-5,0L8.81,18.1,9.45,17h5.11l.64,1.11ZM14.27,15H9.73L8.38,11,12,8.44,15.63,11Zm3.79,2.21-1.14-.1-.79-1.37,1.46-4.34L19,10.93l1,.73c0,.11,0,.22,0,.34A7.94,7.94,0,0,1,18.06,17.21Z" />
</svg>

Which I'm trying to render on a D3 graph by using:

  svg
    .append('image')
    .attr('xlink:href', MyIcon)

How can I change the color of the path in the svg dynamically, as I will be running the append code from a function something like:

const renderIcon = (iconColor) => {
  svg
    .append('image')
    .attr('xlink:href', MyIcon)
    // code to apply color param to the icon path

}

CodePudding user response:

Couldn't find a nice way of actually getting the above working. The solution that I ended up finding was to instead define my icons in an defs element within an svg element in the return statement of my component:

return (
<svg>
  <defs>
    <MyIcon color={myColor1} id="myIcon1" />
    <MyIcon color={myColor2} id="myIcon2" />
  </defs>
</svg>
)

Where MyIcon would look something like:

<g fill={color} id={id}>
  // other svg elements
</g>

And then use them by appending a use element to the svg element and passing in the icons id attribute:

svg.append('use').attr('href', '#myIcon1');
svg.append('use').attr('href', '#myIcon2');
  • Related