tanem / react-svg

:art: A React component that injects SVG into the DOM.

Home Page:https://npm.im/react-svg

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Setting color

u-rogel opened this issue · comments

Thanks for the useful library!

My use case is mostly to through in SVG icons. I was looking for an option to change the icon color and saw it was not straight forward. Using normal CSS rules or CSS-in-JS libraries didn't do the job since I couldn't make it icon specific. If I would use CSS to set a <path> stroke to have color then also a path without the stroke property will received this style. I looked for an option to change only the already given stroke and fill attributes to the color I wanted.
The place where I can access the SVG content is in beforeInjection function, but then I needed to write kind of a work around. I ended up running a recursion on the SVG elements and changing fill and stroke where found.

const replaceElementColor = (element, color) => {
  if (!element || !color) return;
  if (element.hasAttribute && element.hasAttribute('fill')) {
    element.setAttribute('fill', color);
  }
  if (element.hasAttribute && element.hasAttribute('stroke')) {
    element.setAttribute('stroke', color);
  }
  element.childNodes.forEach((child) => {
    replaceElementColor(child, color);
  });
};

const ReactSvgWrapper = ({ color }) => (
  <ReactSvg
    svg={'svg-url'}
    beforeInjection={(svg) => {
      svg.childNodes.forEach((child) => {
        replaceElementColor(child, color);
      });
    }}
  />
);

Could you think of a simpler approach?
If not, then I would gladly leave it around for developers with similar issues.

Hey @u-rogel, your approach looks OK. There are related examples here in case you haven't seen them already:

Closing due to inactivity, feel free to comment if you'd like it re-opened 🙏

The before-injection case is somewhat close to what I did, so I guess I am within the scope.
Thanks for the reply