Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

svg not rendering correctly when used with by multiple react components

Context

I have an SVG that is used by two different React components (A and B) on the same page.

Problem

When component A is assigned 'display: none' css property, the svg in component B does not render correctly.

Example

componentA {
 display: none;
}
componentB {
 display: block;
}

SVG does not render correctly

componentA {
 display: block;
}
componentB {
 display: block;
}

SVG renders correctly

I suspect it may be an issue with my svg but I am not sure as I am new to react. Below is the svg code.

<svg
  id={id}
  data-name={id}
  xmlns="http://www.w3.org/2000/svg"
  width={width}
  height={height}
  viewBox="0 0 498 305.84">
  <defs>
    <clipPath id="clip-path">
      <path
        fill="none"
        d="M354.47 137.84c1.75-22.18-9.65-52.24-34-73.15-15.94 51.41 30.59 56.14 34 73.15" />
    </clipPath>
    <linearGradient
      id="linear-gradient"
      x1="-146.72"
      y1="416.08"
      x2="-143.8"
      y2="416.08"
      gradientTransform="matrix(7.8 0 0 -7.8 1469.73 3349.9)"
      gradientUnits="userSpaceOnUse">
      <stop offset="0%" stopColor="#62bb46" />
      <stop offset="100%" stopColor="#a2d28a" />
    </linearGradient>
  </defs>
  <g id="Leaf">
    <path
      clipPath="url(#clip-path)"
      fill="url(#linear-gradient)"
      d="M286.058 69.72l66.622-18.076 22.032 81.205-66.622 18.074z" />
    <path
      fill="#62bb46"
      d="M320.48 64.69c23.64 2.71 53.94 33.25 34 73.15 1.76-22.18-9.65-52.24-34-73.15" />
  </g>
</svg>
like image 337
Hamed Avatar asked Oct 17 '22 07:10

Hamed


1 Answers

I had a simple workaround that worked for me at least.

The only change I would do is append the unique id to each of the elements with an id attribute,

    <svg
      id={id}
      data-name={id}
      ...
      <defs>
        <clipPath id={`clip-path-${id}`}>
          ...
        </clipPath>
        <linearGradient
          id={`linear-gradient-${id}`}
         ...
        </linearGradient>
      </defs>
      <g id={`Leaf-${id}`}>
        <path
          clipPath={`url(#clip-path-${id})`}
          fill={`url(#linear-gradient-${id})`}
          ...
         />
      </g>
    </svg>

By doing so, it is always assured that SVG will have unique id on different components.

like image 85
KRRISH96 Avatar answered Nov 15 '22 05:11

KRRISH96