gilbarbara / react-inlinesvg

An SVG loader component for ReactJS

Home Page:https://codesandbox.io/s/github/gilbarbara/react-inlinesvg/tree/main/demo

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Change preProcessor dose not trigger re-render

BB-fat opened this issue · comments

commented

Describe the bug

I wrapped InlineSVG as a component that can change the color in svg, but when I change the incoming color, that is, when the proProcessor changes, re-rendering is not triggered, and the color of svg on the page is still the original.

Your minimal, reproducible example

none

Steps to reproduce

const XWSvg: FC<XWSvgProps> = ({ color, ...otherProps }) => {
  const preProcessor = useCallback<PreProcessorCallback>(
    (code) => {
      if (color) {
        const svg = new DOMParser().parseFromString(code, 'image/svg+xml');

        const e1 = svg.querySelectorAll('[fill]:not([fill="none"])');
        e1.forEach((e) => e.setAttribute('fill', color));

        const e2 = svg.querySelectorAll('[stroke]:not([stroke="none"])');
        e2.forEach((e) => e.setAttribute('stroke', color));

        return svg.documentElement.outerHTML;
      } else {
        return code;
      }
    },
    [color]
  );

  return <SVG {...otherProps} preProcessor={preProcessor} />;
};

// ---
<XWSvg src={svgIcon} color={isActive ? theme.palette.primary.main : 'green'} />;

Expected behavior

The svg can update the color when I modify the color field.

How often does this bug happen?

Every time

Screenshots or Videos

No response

Platform

No response

react-inlinesvg version

4.0.3

TypeScript version

4.4.3

Build tool

webpack

Additional context

No response

Hey @BB-fat

You can easily fix that by setting the color as the key for the element. When the color changes, it will instantiate the SVG component again.

return <SVG key={color} {...otherProps} preProcessor={preProcessor} />