When constructing a UI, the significance of SVG cannot be overstated. As the code base expands, the utilization of SVG also grows. In this blog, we will explore the top three methods for rendering SVG and identify the most optimal solution among them.
Initial Approach
Initially, the approach was to use a simple <img>HTML tag:
There is a delay before it appears on the screen, and styling the SVG is not possible in this scenario.
Most Common Approach
We’ll craft an SVG component named PlusSVG.tsx, allowing us to conveniently utilize this component in various locations.
We will render the previously created component in the relevant sections as needed.
Pros
Easy to implement, customizable styling, and no flickering issues.
Cons
If you use the same SVG in multiple places, it adds unnecessary weight to the DOM, leading to an increase in bundle size, especially when dealing with numerous SVGs in your project.
Most Effective Method: SVG Sprites
Creating a reusable “Icon” component for rendering SVG icons.
Developing a “Sprite” component to handle all SVG icons.
Render the SpriteSvg in the App component
How to use:
How to Handle Large Sprites in Large Projects
Create an SVG file for sprites and place it within the public folder.
Pre-load the mentioned sprite.svg file by adding the following to index.html:
Utilize the previously constructed Icon.tsx component by passing the respective name to it.