Creating re-useable and colorable SVG icons in Vue.js

Chris Backhouse
3 min readJun 3, 2022

--

Photo by Alexander Shatov on Unsplash

How to create a color changeable icon component in Vue.js

I recently used the PINGCRM Laravel-vue Inertia project as a starting point for a new project and they have an Icon component with half a dozen SVG icons defined.

They use a basic v-if and then v-else-if checking the name, like this:

And this works great for a small demo project but notice that the icons are pre-colored and you can’t recolour them using CSS classes in the parent node.

I thought that there must be a more flexible way to use SVG icons so I googled “how to change SVG colours” and came across this post which explains a neat work-around for setting up re-useable SVG components.

Here is a summary; you setup your SVG icon library as ‘display: none’ and then include each svg icon as a new symbol element like this:

Note that each symbol has a unique ID attribute which we will use in a moment.

Then, when we want to use this icon in our HTML code we use the ‘use’ svg tag which points back to our symbol definition above:

Taking that one step further, if we then modify each SVG element to use a fill color of “currentColor” so that we can then over-ride the icon color using CSS.

Note: that depending on your SVG, you may want to colorise the fill color or the stroke color.

With Heroicons this would depend on whether you are using the outline or the solid version of an icon — be careful if you mix them up, as it can get really confusing!

The currentColor variable is available in most modern browsers and takes the color from the parent item.

This means that we can then create a view component and colorise the svg by setting the CSS color attribute on it’s parent

<svg :width=”vWidth” :height=”vHeight” :class=”vIconColor”>

So, going back to the original Icon component that I mentioned at the start, we can then get rid of all those v-else-if statements and replace them with symbols as follows:

We therefore need to create a component to define the icons with symbols. We can then include this at the top of every page, perhaps in our layout just after the body tag. I call this component IconSetup

IconSetup.vue
layout.vue

Next we need an icon component, so let’s call this Icon.vue

Icon.vue

I’m using Tailwind CSS, so you will notice this uses hover: modifiers as well.

You then use this component in your code like this:

<icon iconName=”chevron-right” iconColor=”primary” width=14 height=14 iconHoverColor=”warning” />

above: I’m using custom colors in Tailwind, primary and warning, based on the DaisyUI Tailwind theme.

I hope you find this useful!

--

--

Chris Backhouse

A full stack developer using PHP, Symfony, Laravel, Vue.js, Inertia and a whole lot more!