Streamline SVG Sprites in Your React Applications
simprl
Posted on August 28, 2023
Hello, wonderful devs! If you frequently work with SVG icons in your React projects and find the process of managing and referencing them a bit cumbersome, today's your lucky day. I present to you the react-svg-sprite-generator!
What is react-svg-sprite-generator?
The react-svg-sprite-generator is a CLI tool designed for React.js developers. It helps generate SVG sprites from a directory filled with SVG files, automatically preparing them for use within React applications. The real magic, though? The generated names.js file, which not only contains the constants for your SVG icons but also inline Base64 encoded previews!
Why Use It?
- Ease of Use: With a simple command, transform your directory of SVG icons into an organized sprite with accompanying JS and markdown documentation.
- IDE Support: In IDEs like VSCode and Webstorm, benefit from autocompletion with actual image previews. It boosts your development speed, especially when selecting icons.
- No Memorization: Say goodbye to remembering exact SVG paths or names. With autocompletion and inline previews, pick the right icon every time.
Getting Started
Installation
npm i --save-dev react-svg-sprite-generator
Generate SVG sprite
Simply run:
svgsprite
Or specify source and destination:
svgsprite --src ./path/to/your/svg/directory --dest ./path/for/generated/files
Structure
After the command runs, your icons are now structured in a neat manner, with accompanying JS and markdown documentation.
For instance, with two icons icon1.svg and icon2.svg, you get:
src
└── components
└── Icon
├── sprite.svg
├── names.js
└── Readme.md
Usage in React
import * as IconNames from './names.js';
import spriteUrl from './sprite.svg';
interface IconProps {
name: (typeof IconNames)[keyof typeof IconNames];
}
const Icon = ({ name }: IconProps ) => {
return (
<svg>
<use href={`${spriteUrl}#${name}`} />
</svg>
);
};
export default Icon;
import * as IconNames from './names.js';
import Icon from './Icon.js';
<Icon name={IconNames.ICON1} />
Wrapping Up
The react-svg-sprite-generator is here to revamp how you deal with SVG icons in React. Try it out and let's make icon management in React a breeze!
If you find the library useful, consider giving it a star ⭐ on GitHub. Feedback, PRs, and issues are always welcome!
Posted on August 28, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.