Custom Icons

The Dynamic Icon Component is designed to efficiently load and display SVG icons dynamically in a Nuxt project. It provides a placeholder while the icon is loading and includes transition effects when the icon is active. This component can also be used to easily change the color of SVG icons dynamically, without needing separate icon files for each color.

  • Ensure that SVG icons are stored in the ~/assets/icons/ directory.
  • Icons are dynamically imported using import().
  • If an icon is missing, an error is logged in the console.
  • You can change the color of an icon by modifying the fill attribute of the SVG code.
Usage
<template>
  <template>
    <component :is="iconComponent" class="svg-icon" v-if="iconComponent" />
  </template>

  <script setup>
    const props = defineProps({
      name: {
        type: String,
        required: true,
      },
    });

    const iconComponent = shallowRef(null);

    const loadIcon = async (name) => {
      try {
        iconComponent.value = (
          await import(`~/assets/icons/${name}.svg?component`)
        ).default;
      } catch (error) {
        console.error(`Icon ${name} not found in assets/icons directory.`);
      }
    };

    onMounted(() => {
      loadIcon(props.name);
    });

    watch(
      () => props.name,
      (newName) => {
        loadIcon(newName);
      }
    );
  </script>
</template>
Props
Prop NameTypeDefaultDescription
nameStringRequiredThe name of the icon file (without .svg extension).
isActiveBooleanfalseEnables an active state that modifies the icon's color.
placeholderWidthString24pxDefines the width of the placeholder.
placeholderHeightString24pxDefines the height of the placeholder.
placeholderClassString''Additional CSS classes for the placeholder.
Example usage
<template>
  <DynamicIcon
    name="settings"
    :isActive="true"
    placeholderWidth="32px"
    placeholderHeight="32px"
  />
</template>
Step to Enable Color Change in Icons

Update your SVG icon to enable color flexibility, modify the fill attribute in your SVG files stored in the ~/assets/icons/ directory. Change any fill="#color" to fill="currentColor". This allows the icon's color to be controlled via CSS, using the color property.

- SVG color
fill="#fffff"

- To update SVG color
fill="currentColor"
Conclusion

The Dynamic Icon Component provides a flexible and efficient solution for handling SVG icons in a Nuxt project. It enhances performance by dynamically loading assets while offering customization options for a seamless UI experience. Also, By using the currentColor property in your SVGs, you can easily modify the icon color dynamically with CSS, making your project more efficient and reducing the need to store multiple versions of the same icon.