JSFiddle - React, Tailwind, and code Playground

by John Pisello

HTML

<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/select2.min.css">
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/select2.min.js"></script>
<select></select>

CSS

select {
  width: 100%;
}

JavaScript

function buildPills() {
  return [{
    id: "",
    text: ""
  }, {
    id: "opt0",
    text: "Option 0"
  }, {
    id: "opt1",
    text: "Option 1"
  }, {
    id: "opt2",
    text: "Option 2"
  }, {
    id: "opt3",
    text: "Option 3"
  }];
}

$.fn.select2.defaults.set("allowClear", true);
$.fn.select2.defaults.set("closeOnSelect", true);
$.fn.select2.defaults.set("minimumResultsForSearch", 17);
$.fn.select2.amd.define('select2/data/customAdapter', ['select2/data/array', 'select2/utils'],
  function(ArrayAdapter, Utils) {
    function CustomDataAdapter($element, options) {
      CustomDataAdapter.__super__.constructor.call(this, $element, options);
    }
    Utils.Extend(CustomDataAdapter, ArrayAdapter);
    CustomDataAdapter.prototype.updateOptions = function(data) {
      const selected = this.$element.select2("data");
      this.$element.find('option').remove();
      for (const item of data) {
      	for (const sel of selected) {
        	item.selected = (item.id === sel.id);
        }
      }
      this.addOptions(this.convertToOptions(data));
    };
    return CustomDataAdapter;
  });

$("select").select2({
	/* data: buildPills(), */
  dataAdapter: $.fn.select2.amd.require('select2/data/customAdapter'),
  disabled: false,
  multiple: false,
  placeholder: "Placeholder"
})
.on('select2:opening', function(e) {
  let pills = buildPills();
  $(this).data("select2").dataAdapter.updateOptions(pills);
})
;