Skip to content

elderapo/react-svg-unique-id

Repository files navigation

react-svg-unique-id

styled with prettier Greenkeeper badge Build Status AppVeyor Coveralls Dev Dependencies FOSSA Status

SVG processors like SVGO optimize SVG ids which often results in duplicated ids across multiple SVGs. This library tries to fix that by replacing all children ids and id references (#id, url(#id)) in SVG tags with unique generated ids like ___SVG_ID__10__0___.

How to install

yarn add react-svg-unique-id
# or
npm install react-svg-unique-id

Usage

import * as React from 'react'
import { SVGUniqueID } from 'react-svg-unique-id'

export const SVG1 = () => (
  <SVGUniqueID>
    <svg width="100%" height="100%" viewBox="0 0 60 64">
      <defs>
        <linearGradient id="prefix__bga" /> // prefix__bga => ___SVG_ID__0__0___
      </defs>
      <g fillRule="nonzero" fill="none">
        <use xlinkHref="#prefix__bga" /> // #prefix__bga => #___SVG_ID__0__0___
        <path fill="url(#prefix__bga)" /> // url(#prefix__bga) => "url(#___SVG_ID__0__0___)
      </g>
    </svg>
  </SVGUniqueID>
)

export const SVG2 = () => (
  <SVGUniqueID>
    <svg width="100%" height="100%" viewBox="0 0 60 64">
      <defs>
        <linearGradient id="prefix__bga" /> // prefix__bga => ___SVG_ID__1__0___
      </defs>
      <g fillRule="nonzero" fill="none">
        <use xlinkHref="#prefix__bga" /> // #prefix__bga => #___SVG_ID__1__0___
        <path fill="url(#prefix__bga)" /> // url(#prefix__bga) => url(#___SVG_ID__1__0___)
      </g>
    </svg>
  </SVGUniqueID>
)

If both of these SVGs were not wrapped in SVGUniqueID component there would be an id collision since two html elements would have prefix__bga as thier id.

License

FOSSA Status