DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Eray Ates
Eray Ates

Posted on • Updated on

Make Icon Component

When using an icon in a web framework, a predefined component is used like fontawesome. But if you have just a few icons or want to use a custom icon, I will show you how to make your own component with SVG.

For SVG, I get from https://iconmonstr.com/ which is a very cool icons have.

<script lang="ts">
/* eslint-disable no-unused-vars */

enum IconTypes {
  plus = "M24 9h-9v-9h-6v9h-9v6h9v9h6v-9h9z",
  arrow = "M8.122 24l-4.122-4 8-8-8-8 4.122-4 11.878 12z",
}
type IconTypesString = keyof typeof IconTypes;

type PosTypes = "left" | "down" | "up" | undefined;

export let icon: IconTypesString;

export let height = "24";
export let width = "24";

export let className: string = undefined;
export let position: PosTypes = undefined;

const totalClass = [className, position].join(" ");
</script>

<svg xmlns="http://www.w3.org/2000/svg"
  class={totalClass ? totalClass : undefined}
  width="{width}"
  height="{height}"
  viewBox="0 0 24 24">
  <path d={IconTypes[icon]}/>
</svg>

<style lang="scss">
  .left {
    transform: rotate(180deg);
  }

  .down {
    transform: rotate(90deg);
  }

  .up {
    transform: rotate(-90deg);
  }
</style>
Enter fullscreen mode Exit fullscreen mode

Added an enumerate to list of icons as type so when we using this component, it will help autocomplete.
Transformation CSS variable using for not repeating icons also added custom className props to control your icon in CSS part.
I fixed viewBox to 0 0 24 24 so width and height can works. But if your SVG is different than 24-24 you should update viewBox after that you can change value with width and height.

That's all welcome your new icon component.

<Icon icon="arrow" className="arrow" position="left"/>
Enter fullscreen mode Exit fullscreen mode

If you need to middle of the content just wrap with flex use align-items center.

Top comments (0)

Take Your Github Repository To The Next Level

>> Check out this classic DEV post <<