Inline SVG Unique ID
raw JSON → 1.5.0 verified Sat Apr 25 auth: no javascript
A Babel plugin (v1.5.0) that transforms inline React SVG components at build time to replace hardcoded definition IDs with runtime-generated unique IDs, preventing ID collisions when the same SVG is used multiple times on a page. Requires the companion runtime package @inline-svg-unique-id/react. Stable, updated sporadically, maintained by a single contributor. Key differentiator: SSR-friendly with a context provider for custom ID prefixes, unlike alternatives that rely on random hashes without SSR support.
Common errors
error Error: Cannot find module '@inline-svg-unique-id/react' ↓
cause The runtime dependency is not installed.
fix
npm install @inline-svg-unique-id/react
error The id 'grad1' is already defined, skipping definition ↓
cause Missing Provider wrapper causing ID collision warning from browser.
fix
Wrap your app with <Provider> from '@inline-svg-unique-id/react'.
error Attempted import error: 'useUniqueInlineId' is not exported from '@inline-svg-unique-id/react' ↓
cause Using incorrect import syntax (default import instead of named).
fix
Use import { useUniqueInlineId } from '@inline-svg-unique-id/react'
Warnings
deprecated The plugin is not actively maintained; last update was in 2021. ↓
fix Consider alternatives if you need ongoing support.
gotcha The runtime package @inline-svg-unique-id/react is required and must be installed separately. ↓
fix Run: npm install @inline-svg-unique-id/react
gotcha Provider idPrefix prop is evaluated only once; changing it on rerenders has no effect. ↓
fix If you need dynamic prefixes, create a new Provider instance.
Install
npm install babel-plugin-react-inline-svg-unique-id yarn add babel-plugin-react-inline-svg-unique-id pnpm add babel-plugin-react-inline-svg-unique-id Imports
- default wrong
import babelPluginReactInlineSvgUniqueId from 'babel-plugin-react-inline-svg-unique-id'correctmodule.exports = require('babel-plugin-react-inline-svg-unique-id') - useUniqueInlineId wrong
import useUniqueInlineId from '@inline-svg-unique-id/react'correctimport { useUniqueInlineId } from '@inline-svg-unique-id/react' - Provider wrong
import { UniqueIdGeneratorProvider } from '@inline-svg-unique-id/react'correctimport { Provider } from '@inline-svg-unique-id/react'
Quickstart
// Install: npm install babel-plugin-react-inline-svg-unique-id @inline-svg-unique-id/react
// .babelrc
{
"plugins": ["react-inline-svg-unique-id"]
}
// App.jsx
import { Provider as UniqueIdGeneratorProvider } from '@inline-svg-unique-id/react';
const YourApp = () => (
<UniqueIdGeneratorProvider>
<Icon />
<Icon />
</UniqueIdGeneratorProvider>
);
// Icon.jsx
import { useUniqueInlineId } from '@inline-svg-unique-id/react';
const Icon = () => {
const gradientId = useUniqueInlineId();
return (
<svg>
<defs>
<linearGradient id={gradientId}>
<stop offset="0%" stopColor="red" />
</linearGradient>
</defs>
<ellipse fill={`url(#${gradientId})`} />
</svg>
);
};