Hacking Font-Awesome for Custom SVG Icons
https://fontawesome.com is really awesome project. There are multiple cool things I like about font-awesome.
- You can do lots of operation over icon — change color, rotate, scale etc.
- Tree Shaking — include icons which are needed.
- I love React and react package is available —
Lets “Hack” font-awesome for our purpose.
First we will see, how to include icon from font-awesome library and then we will Hack it to use “custom svg icon”.
Icon using CSS
Above icon can be added to your application using following code.
FA Icon using React
Now, lets see, The React.js Code for above icon.
<Icon color="red" size="6x" rotation={270} icon="ambulance" />
Please note the line no 8. If you run the application and see the console.log, you will find a JavaScript Object which is called Icon-Definition.
Lets check what is the icon-defintion object. It looks like this. {Line number 8}
So, font-awesome convert SVG file to this JavaScript Objects.
💡 If we generate icon-definition file for our custom svg icon and add to font-awesome than we will be able use font-awesome for custom svg icons. 💡
Lets do it.
Power of Font-Awesome on Custom SVG Icon
Here is a sample icon from flaticon.com
https://www.flaticon.com/free-icon/car_335049#term=car&page=1&position=4
Here is the SVG file for the above icon.
Next, Let’s try to convert this into the icon file. Check Line 7 to 17
we need to provide viewbox height, width, iconName and Path information.
in SVG file, you will see there are 3 `path`. I just combined all 3 into one line which is the 5th argument in icon definition.
And now, here is the result.
Conclusion
It is quite easy to achieve “Power of Font-Awesome” on our custom svg icons. If you are creating “Custom fonts” or “SVG sprites” etc, you can try this technique. You can create a private(?) git repo to store all your icons which can be used across all multiple projects in your company.
Let me know if you have any suggestions or improvement over this approach.