Blog

Prevent SVG Gradient and Mask ID Collisions in React

Keep inline SVG references unique when the same icon component appears more than once.

Cover image for Prevent SVG Gradient and Mask ID Collisions in React

Recognize the repeated-ID problem

An inline SVG may define a gradient, mask or clipping path with an ID such as paint0. A second copy of that SVG can introduce the same ID into the document. References like url(#paint0) may then resolve to an unintended definition. Symptoms can include colors changing between instances or an illustration breaking only when another component is present.

Create a stable ID per component instance

In React, useId provides an ID suitable for relationships within a component. Derive names for the gradient and mask from that value, then use the same names in the corresponding references. Avoid generating random IDs during rendering: server and client output need to agree. Keep the relationship visible in the source so future edits do not rename one side alone.

Prefixing a file is only part of the solution

An optimizer can add a prefix to distinguish different source files. That helps when two separate illustrations use generic IDs, but a fixed prefix will repeat when one component renders multiple times. Use an instance-specific strategy for repeated components. External SVG image files have a different document boundary, so identify how the artwork is embedded before changing its internals.

Test several copies together

Render two copies with different colors beside each other and add a third inside a dialog or list. Inspect both the visual output and generated IDs. Check server-rendered pages after hydration as well as client-side navigation. A component that looks correct alone is not enough evidence that its internal references remain reliable throughout the interface.

Reference and further reading

Official documentation

Keep reading

Previous post

Prepare SVG Icons for Print and PDF Layouts

Check physical size, line weight and exported PDF output before sending vector artwork to print.

Read article