JSFiddle - React, Tailwind, and code Playground
HTML
<script src="https://select2.github.io/dist/js/select2.full.js"></script>
<script src="https://select2.github.io/vendor/js/bootstrap.min.js"></script>
<script src="https://select2.github.io/vendor/js/prettify.min.js"></script>
<link rel="stylesheet" href="https://select2.github.io/vendor/css/bootstrap.min.css">
<link rel="stylesheet" href="https://select2.github.io/dist/css/select2.min.css">
<link rel="stylesheet" href="https://select2.github.io/vendor/css/font-awesome.min.css">
<link rel="stylesheet" href="https://select2.github.io/vendor/css/prettify.css">
<select class="js-data-example-ajax" style="width:100%">
<option value="3620194" selected="selected">Select a value......</option>
</select>
JavaScript
function formatRepo (repo) {
if (repo.loading) return repo.text;
var markup = '<div class="clearfix">' +
'<div class="col-sm-1">' +
'<img src="' + repo.owner.avatar_url + '" style="max-width: 100%" />' +
'</div>' +
'<div clas="col-sm-10">' +
'<div class="clearfix">' +
'<div class="col-sm-6">' + repo.full_name + '</div>' +
'<div class="col-sm-3"><i class="fa fa-code-fork"></i> ' + repo.forks_count + '</div>' +
'<div class="col-sm-2"><i class="fa fa-star"></i> ' + repo.stargazers_count + '</div>' +
'</div>';
if (repo.description) {
markup += '<div>' + repo.description + '</div>';
}
markup += '</div></div>';
return markup;
}
function formatRepoSelection (repo) {
return repo.full_name || repo.text;
}
$(document).ready(function(){
$(".js-data-example-ajax").select2({
ajax: {
url: "https://api.github.com/search/repositories",
dataType: 'json',
delay: 250,
data: function (params) {
return {
q: params.term, // search term
page: params.page
};
},
processResults: function (data, page) {
// parse the results into the format expected by Select2.
// since we are using custom formatting functions we do not need to
// alter the remote JSON data
return {
results: data.items
};
},
cache: true
},
escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
minimumInputLength: 1,
templateResult: formatRepo, // omitted for brevity, see the source of this page
templateSelection: formatRepoSelection // omitted for brevity, see the source of this page
});
});