DEV Community

Eray Ates
Eray Ates

Posted on • Edited on

3 1

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.

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay