use-svg-sprite
The @bento/use-svg-sprite package provides a hook that registers inline
SVG illustrations into a shared sprite sheet and returns a reusable component.
This makes it easy to keep your icons consistent and efficient across the app.
This approach ensures your icons are only defined once in the DOM and reused
efficiently across your app, improving performance and maintainability.
Installation
npm install --save @bento/use-svg-sprite
useSVGSprite
The package exposes a useSVGSprite hook that creates a new symbol element
for the provided illustration and adds it to the sprite sheet.
The hook returns a React element that references the newly added symbol.
Basic Usage
import { useSVGSprite } from '@bento/use-svg-sprite';
import React from 'react';
export function BasicUsage() {
const Icon = useSVGSprite(
'check',
<svg viewBox="0 0 24 24" width={24} height={24}>
<path d="M5 13l4 4L19 7" stroke="currentColor" strokeWidth="2" fill="none" />
</svg>
);
return <div>{Icon}</div>;
}
As seen from the example above, the useSVGSprite hook takes two arguments:
It returns a React element that renders an <svg> with a <use>
that references a symbol injected into a shared sprite sheet.
Multiple Icons Example
You can define and render multiple icons with different names.
import { useSVGSprite } from '@bento/use-svg-sprite';
import React from 'react';
export function MultipleIcons() {
const Check = useSVGSprite(
'check',
<svg viewBox="0 0 24 24" width={24} height={24}>
<path d="M5 13l4 4L19 7" stroke="green" strokeWidth="2" fill="none" />
</svg>
);
const Alert = useSVGSprite(
'alert',
<svg viewBox="0 0 24 24" width={24} height={24}>
<circle cx="12" cy="12" r="10" stroke="red" strokeWidth="2" fill="none" />
<line x1="12" y1="8" x2="12" y2="12" stroke="red" strokeWidth="2" />
<circle cx="12" cy="16" r="1" fill="red" />
</svg>
);
return (
<div>
{Check}
{Alert}
</div>
);
}
When using SVG icons with useSVGSprite, three attributes are crucial for optimal
performance and visual consistency:
viewBox: This attribute defines the coordinate system and aspect ratio of your
SVG. It ensures your icon scales correctly and maintains its proportions when
resized. Without a proper viewBox, icons might appear distorted or incorrectly
positioned.
width and height: These attributes are essential for preventing layout shifts
during page load. By specifying these dimensions, the browser can reserve the
correct amount of space for the icon before it's fully rendered. This improves
the Cumulative Layout Shift (CLS) metric and overall user experience.