SvgIcon as a component

Manage Icons with multiple colors in an optimised way

ยท

2 min read

Hey guys ๐Ÿ‘‹๐Ÿป,

Today am going to write about a challenge I faced while working with svg icons.

Initially in our app, we were using font-awesome icons(css pkg) but later we need more attractive icons, so we designed more customised icons & export it in svg format.

While using css pkgs, it would be easy to change color of icons because we can directly add css to styles.

<style>
.fa-angle-right {
  color: "#000000"
}
</style>

But what if we want to change the color of svg icon? And here I had various thoughts...

  • Changing the color in svg file is enough?
  • If so what can we do to use same icon in various components while having different colors in different components?
  • Do we need to have each copy of each color for the same icon???

Noo Dood...๐Ÿ˜’

The best way to manage is, here we need to add SvgIcon as a component. And how can we do that...

  1. First create a component file, which prompts for props values 'icon-name' & 'icon-color'.
  2. Based on the given props values, render the icon.

Code in vuejs

SvgIcon.vue

<template>
  <div
    v-html="svg"
  />
</template>

export default {
  name: 'SvgIcon',
  props: {
    iconName: {
      type: String,
      required: true
    },
    iconColor: {
      type: String,
      default: '#656D71'
    }
  },
  data () {
    return {
      svg: null
    }
  },
  watch: {
    iconColor: {
      handler: 'populateData',
      immediate: true
    }
  },
  methods: {
    populateData () {
      switch (this.iconName) {
        case 'AngleRight':
          this.svg = `<svg width="24" height="24" viewBox="0 0 24 24" fill="none" 
xmlns="http://www.w3.org/2000/svg">
    <path d="M13.1727 12L8.22266 7.05L9.63666 5.636L16.0007 12L9.63666 18.364L8.22266 16.95L13.1727 12Z" fill="${iconColor}"/>
  </svg>`
          break

        case 'Calendar':
          this.svg = `<svg width="20" height="20" viewBox="0 0 20 20" fill="none" 
xmlns="http://www.w3.org/2000/svg">
    <path d="M7.49935 0.833344V2.50001H12.4993V0.833344H14.166V2.50001H17.4993C17.7204 2.50001 17.9323 2.58781 18.0886 2.74409C18.2449 2.90037 18.3327 3.11233 18.3327 10.8033L7.81602 9.62501L9.58352 11.3933L12.5302 8.44668H12.5293Z" fill="${iconColor}"/>
  </svg>`
          break
      }
    }
  }
}
</script>

Import SvgIcon

Now to add 'AngleRight' svg icon in your app with multiple colors,

Test.vue

<template>
  <div>
    <div class="dark"
      <svg-icon
        :icon-name="angle-right"
        :icon-color="#000000"
      />
    </div>

    <div class="light"
      <svg-icon
        :icon-name="angle-right"
        :icon-color="#FFFFFF"
      />
    </div>
  </div>
</template>

<script>
import SvgIcon from './SvgIcon';

export default {
  name: "Test",
  components: { SvgIcon }
}
</script>

In the similar way we can also manage svg icon size

ย