How to implement svg icons in a Shopify theme

Here is in my opinion the best way to organise and implement svg icons in a Shopify theme. Everything is kept in one file with the possibility of adding or updating new icons.

To achieve this we will be using the Shopify snippets directory. By default Shopify Dawn theme has every icon as a separate file in the snippets directory. This is ok but we can make it better.

{% comment %}
  Renders the svg icon

  Usage:
    {% render 'custom-icons', icon:'icon-name' %}

  Accepts:
  - icon: {String} (required) The name of the icon, must match the name in the when statement

{%- liquid
    assign custom-icons = icon
-%}

<span class="icon" aria-hidden="true">
    {% case custom-icons %}
    {% when 'user' %}
        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" class="icon-user">
            <path d="M19 21V19C19 17.9391 18.5786 16.9217 17.8284 16.1716C17.0783 15.4214 16.0609 15 15 15H9C7.93913 15 6.92172 15.4214 6.17157 16.1716C5.42143 16.9217 5 17.9391 5 19V21" stroke="currentColor" stroke-width="1.2" stroke-linecap="square"/>
            <path d="M12 11C14.2091 11 16 9.20914 16 7C16 4.79086 14.2091 3 12 3C9.79086 3 8 4.79086 8 7C8 9.20914 9.79086 11 12 11Z" stroke="currentColor" stroke-width="1.2" stroke-linecap="square"/>
          </svg>
    {% when 'cart' %}
        <svg width="44" height="44" viewBox="0 0 44 44" fill="none" xmlns="http://www.w3.org/2000/svg" class="icon icon-cart">
            <rect width="44" height="44" rx="22" fill="currentColor"/>
            <path d="M18 32C18.5523 32 19 31.5523 19 31C19 30.4477 18.5523 30 18 30C17.4477 30 17 30.4477 17 31C17 31.5523 17.4477 32 18 32Z" fill="currentColor" stroke="currentColor" stroke-width="1.2" stroke-linecap="square"/>
            <path d="M27 32C27.5523 32 28 31.5523 28 31C28 30.4477 27.5523 30 27 30C26.4477 30 26 30.4477 26 31C26 31.5523 26.4477 32 27 32Z" fill="currentColor" stroke="currentColor" stroke-width="1.2" stroke-linecap="square"/>
            <path d="M11.05 12.05H13.05L15.71 24.47C15.8076 24.9249 16.0607 25.3315 16.4258 25.6199C16.7908 25.9083 17.245 26.0604 17.71 26.05H27.49C27.9452 26.0493 28.3865 25.8933 28.7411 25.6079C29.0956 25.3224 29.3422 24.9246 29.4401 24.48L31.09 17.05H15.0001" stroke="currentColor" stroke-width="1.2" stroke-linecap="square"/>
        </svg>
    {% else %}
      <!-- {{ icon | capitalize }} icon not found -->
    {% endcase %}
</span>

Then use the bellow snippet anywhere in the theme files to include the icon:

{% render 'custom-icons', icon:'icon-name' %}

From the example we can specify any of the icons by the name user or cart. We can then add new icons bellow with adding a new when statement. If needed you can specify a custom class to each icon and make sure that stroke or fill use the value of currentColor. That will inherit the color that is set on the parent element of the icon and can be changed with CSS.