JSFiddle - React, Tailwind, and code Playground
HTML
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>
<select class="js-select2">
</select>
CSS
.js-select2{
width: 300px;
}
JavaScript
$(".js-select2").select2({
ajax: {
url: "https://api.myjson.com/bins/rfr3",
delay: 250
}
});
var $select = $('.js-select2');
$select.select2({
ajax: {
url: "https://api.myjson.com/bins/rfr3",
delay: 250
}
}); // initialize Select2 and any events
var $option = $('<option selected>Loading...</option>').val("3");
$select.append($option).trigger('change'); // append the option and update Select2
$.ajax({ // make the request for the selected data object
type: 'GET',
url: 'https://api.myjson.com/bins/290rj',
dataType: 'json'
}).then(function (data) {
// Here we should have the data object
console.log(data);
$option.text(data.text).val(data.id); // update the text that is displayed (and maybe even the value)
$option.removeData(); // remove any caching data that might be associated
$select.trigger('change'); // notify JavaScript components of possible changes
});