Skip to main content Skip to footer

Inserting a Custom SVG Icon into ComboBox in JavaScript

Custom SVG Icon in ComboBox

Background:

Wijmo ComboBox allows you to customize how items are displayed in the drop-down list. One effective way to enhance usability is to insert custom SVG icons next to each item, useful for visual categories, status indicators, or branding.

Steps to Complete:

  1. Prepare a data source that includes an icon identifier or SVG source per item.
  2. Use a custom itemFormatter to render the SVG icon alongside the item text.
  3. Optionally apply CSS to adjust spacing and alignment.

Getting Started:

Prepare a data source that includes an icon identifier or SVG source per item

Each ComboBox item contains both a label and an SVG string. We include an icon property in each data object so the formatter can render it.

<div id="theCombo"></div>
import * as wjcInput from '@mescius/wijmo.input';

const items = [
  {
    name: 'Home',
    icon: '<svg width="16" height="16"><!-- SVG markup for home --></svg>'
  },
  {
    name: 'Work',
    icon: '<svg width="16" height="16"><!-- SVG markup for work --></svg>'
  },
  {
    name: 'Settings',
    icon: '<svg width="16" height="16"><!-- SVG markup for settings --></svg>'
  }
];
  • Each object has a name and an icon field.
  • The icon field contains inline SVG markup.
  • This structure lets the ComboBox render both text and icon.

 

Use a custom itemFormatter to render the SVG icon alongside the item text

The itemFormatter function allows full control over how each dropdown item is rendered. We inject the SVG icon and the item text into the DOM.

const combo = new wjcInput.ComboBox('#theCombo', {
  itemsSource: items,
  displayMemberPath: 'name',
  itemFormatter: function (index, item) {
    return `
      <div class="combo-item">
        <span class="combo-icon">${item.icon}</span>
        <span class="combo-text">${item.name}</span>
      </div>
    `;
  }
});
  • displayMemberPath tells the ComboBox which field is the display text.
  • itemFormatter overrides the default rendering of each item.
  • We inject the SVG markup directly into the item template.

 

Optionally apply CSS to adjust spacing and alignment

CSS ensures the icon and label are aligned properly and look polished in the dropdown list.

.combo-item {
  display: flex;
  align-items: center;
}

.combo-icon {
  display: inline-block;
  margin-right: 8px;
  width: 16px;
  height: 16px;
}

.combo-text {
  flex: 1;
}
  • .combo-item aligns icon and text horizontally.
  • .combo-icon ensures consistent spacing and sizing.

 

With this JavaScript setup:

  • Each ComboBox entry displays an SVG icon alongside its label.
  • The SVG renders inline without external image requests.
  • The dropdown becomes visually richer and easier to scan.

Happy coding!

Andrew Peterson

Technical Engagement Engineer