Custom SVG icons with Ionic 3

Published: January 06, 2018  •  ionic3, javascript

The Ionic 3 framework provides with the ionicons library a lot of icons out of the box you can use in your Ionic app. But no library contains icons for every use case and sometimes you want to include SVG icons from other libraries.

For this example I downloaded three icons (mobile.svg, qrcode.svg and spades.svg) from the https://icomoon.io library.

To make them accessible to the Ionic app copy the files into the src/assets folder.
Then open the file src/app/app.scss and add this rule.

ion-icon {
  &[class*="custom-"] {
    mask-size: contain;
    mask-position: 50% 50%;
    mask-repeat: no-repeat;
    background: currentColor;
    width: 1em;
    height: 1em;
  }

  &[class*="custom-mobile"] {
    mask-image: url(../assets/mobile.svg);
  }
  &[class*="custom-qrcode"] {
    mask-image: url(../assets/qrcode.svg);
  }
  &[class*="custom-spades"] {
    mask-image: url(../assets/spades.svg);
  }

}

The name does not have start with custom-. You can choose any prefix.

With that scss rule in place you can display the icons in your app, like the icons from the ionicons library, with the ion-icon tag.

<ion-icon name="custom-mobile"></ion-icon>
<ion-icon name="custom-qrcode"></ion-icon>
<ion-icon name="custom-spades"></ion-icon>

When you have a lot of icons you can optimize this by embedding the SVG code directly into the scss file. The browser then only needs to load one css file instead of requesting each SVG file individually.

To convert an SVG file into a dataurl you add the prefix data:image/svg+xml;utf8, and copy and paste the SVG code after the comma.

&[class*="custom-embeddedmobile"] {
 mask-image: url('data:image/svg+xml;utf8,<svg ...> ... </svg>');
}
&[class*="custom-embeddedqrcode"] {
 mask-image: url('data:image/svg+xml;utf8,<svg ...> ... </svg>');
}
&[class*="custom-embeddedspades"] {
 mask-image: url('data:image/svg+xml;utf8,<svg ...> ... </svg>');
}

Screenshot


Source: https://forum.ionicframework.com/t/anyway-to-custom-the-tabbars-icon-with-my-own-svg-file/46131/36

You find the source code for the example on GitHub: https://github.com/ralscha/blog/tree/master/customicons