How handle I correct a SVG icon in React?

1 week ago 16
ARTICLE AD BOX

TL;DWR: It's probably best to keep static files in the public directory, unless you have a specific reason which necessitates keeping them in the src folder instead!

Hi! I'm answering this under the assumption that Vite is being used here, since it is generally the modern standard for React development!

First off, if you're not seeing the icon in dev mode, the simple (but still incorrect — I'll explain this in the next section) fix, is to change your href from

href={`/assets/svg/app-sprite.svg#snow`}

to

href={`src/assets/svg/app-sprite.svg#snow`}

Why this works in Dev mode: In Dev mode, Vite serves assets from the root path. Additionally, assets in the special public folder are also served from the root path, which also explains why your original code works when you move it to the public folder. You can read more about static asset handling in the Vite docs here!


HOWEVER

If you then build your file with a bundler, such as Vite, chances are that you'll find that the project is broken... AGAIN!

The reasoning is that whenever you put a file in src, the bundler assumes whatever file you've put in there, image or otherwise, is a module. Since you're referencing the SVG via a literal string path using href instead of importing the file, the bundler doesn't actually know it's needed! Instead, it will go "Eh, this svg isn't being imported, and modules that aren't imported probably aren't used in the project. Therefore, I shouldn't include this file in the final build because one of my purposes is to minimize build size, and there's no reason to include a file which (I wrongly assume) is unused."

On the other hand, if you put your static assets in the public folder, the bundler will think: "Oh! This directory is where the static files live! I probably shouldn't touch this and should instead include this in the distribution folder as-is; the developer might have hrefs referencing it that I might not know of!"

Thus, it is generally good practice to place static files (images, audio, etc.) in the public folder for the aforementioned reasons.

Hope this helps!

Read Entire Article