How to implement SVG Sprites in React

André Marques
Geek Culture
Published in
2 min readJun 2, 2021

Reading this post I’m sure you’ll probably have some ideas about the benefits of using inline SVG instead of plain <img> tags that point to a local SVG file in your assets folder.

<img src="@assets/cool-icon.svg"></img>

Let’s look at this line, it’s pretty simple and everyone does it but why they shouldn’t do it? Well, if you look at your Network (using browser developer tools) tab when running your application you’ll see that for every image tag you’ll send an HTTP request to your server to retrieve this image. And this can be a serious problem because let’s imagine that you have some condition in your JSX that loads a block of HTML and performs some requests to your backend system. If that block of HTML has icons you can flood your server with unnecessary requests because after all, it’s just icons.

I’m not saying not to use image tags at all, I’m just telling that if you have icons in your application that you want to load think twice about the performance of what you are doing.

What are inline SVGs?

Inline SVGs as the name says, are SVG tags that are directly placed in your code when your page renders, basically:

<svg width="100" height="100">
<circle cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="yellow" />
</svg>

Let’s imagine that you have a file named icon.svg and you want to add this inline SVG to your page. It’s pretty straightforward, for example:

<svg style={{ position: 'absolute'}} width="20" viewBox="0 0 1000 500" fill="white"}>
<use href="@assets/icon.svg" />
</svg>

Voilà! This is how you add inline SVGs to your application.

But this isn’t why you came here (if it was, thank you). This is a nice improvement to your application but you can do better. Imagine that you have 30 icons, you’ll have to do this for all 30? It’s a little bit messy to have this code all over your application if you ask me. To end this small (but useful, hopefully) post I suggest to create SVG sprites, where basically you add all of your SVG icons in one file (icons.svg). The structure of this file is as follows:

<svg xmlns="http://www.w3.org/2000/svg" style="display: none;">
<symbol id="icon-username">
<path>....</path>
</symbol>
<symbol id="icon-password">
<path>....</path>
</symbol>
</svg>

After you have your SVG sprite you’ll have to create a React component that will get the desired icons based on the symbols id (in our icons file).

export const Icon = ({ name, color, size }) => {
return (
<svg style={{position: 'absolute'}} width={size} viewBox="0 0 1000 500" fill={color}>
<use href={Icons + `#${name}`} />
</svg>
)
}

This component will receive the SVG id, color and size, and will add your inline icon into your HTML. Simple and clean as it can be.

--

--