How to use SVG icons in React applications
Less code and few imports
Whatever your application, you’ll probably use icons. I always try to separate images and icons in the assets folder. I like to do that because Icons are more flexible than images, for example, I could change the icon attributes (color, height, width) by coding, and in an image I cannot. The good thing about this flexibility is that you can create an icon component in a generic way.
You probably have seen this:
import iconTest from "../assets/ico-test.svg";<img src={iconTest} />
If we use like that we’ll probably have to import this in everywhere this icon is needed. This isn’t wrong, but we can do better.
We can transform it into a real component, by doing:
import { ReactComponent as IconName } from "../path-icon.svg";<IconName />
Why can we do that?
If you don’t want to load SVG as a separate file, you must remember the curly braces in the import! The React Component import name is significant and tells Create React App that you want a React component that renders an SVG, rather than its filename.
Furthermore, the imported SVG React Component accepts a title prop along with other props that a SVG element accepts. For example:
<IconName width={22} height={22} fill="red" />
I don’t know about you, but for me, this blows my mind with new possibilities. Dynamic icons, dynamic colors, dynamic sizes, etc.
Note from React Documentation: this feature is available with
react-scripts@2.0.0
and higher, andreact@16.3.0
and higher.
To combine this flexibility and earn more performance, I developed a smart way to use icons creating an Icon Selector:
I add an index.js file to the Icon folder, which makes less verbose import. When you add an index.js file into your component folder that file will be the first to be read. You don’t have to write the name of the file and your extension.
The index.js
file:
export { default as Icon } from './Icon';
And now we can import:
import { Icon } from "./Icon";
instead:
import { Icon } from "./Icon/Icon.jsx";
A how-to-use example:
Why should I use it?
The great advantage of this selector is that there is no need to import many SVG files. The only thing you need to do is to import the Icon component.
Don’t forget the difference: Icon used to represent the idea about the thing without any category or many details like the most common word for the thing, and Image is the clear and exact view of what you want to describe.