JSFiddle - React, Tailwind, and code Playground
HTML
<script src="https://code.jquery.com/jquery-2.2.0.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/mithril/0.2.1/mithril.min.js"></script>
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.1/css/select2.min.css">
<script src="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.1/js/select2.min.js"></script>
CSS
.select-container {
padding: 8px;
}
.select-field {
width: 200px;
}
body {
margin: 0;
padding: 0;
}
JavaScript
// Component containing a Select that uses Select2 for functionality.
var S2Component = {
controller: function() {
// this controller does nothing.
// but I like to include it for
// consistency.
},
// Rendered view for S2
view: function(ctrl, attrs) {
var current = attrs.selectedUser;
return m('select', {
class: 'select-field',
config: S2Component._configure
},
attrs.data.map(function(item){
return m('option', {
id: item.id,
value: item.value,
selected: (item.id === current) ? true : false
}, item.name);
})
)
},
// Configure function -- called from m('select') in the view
_configure: function(element, initialized) {
/*
Note: This is a use of the config attribute given to
attributes on mithril objects. Integrating with 3rd
party DOM manipulation (jQuery) needs {config: function(){}} because
that's the attribute that exposes the real DOM element (as opposed to
the virtual dom element) in the corresponding function so you can access
and manipulate it.
the function at the config property in attrs is passed the real DOM element
(element), and whether or not it exists in the page (initialized)
Anyways, let's look at using Select2 now.
*/
// Ensure Externals exist, otherwise we'll error out.
if(!(jQuery && jQuery.fn.select2))
return console.error('You need jquery and Select2 in the page')
// jQuery element
var lmnt = $(element);
// If this hasn't been initialized yet:
if(!initialized) {
lmnt.select2({
tags: "true",
placeholder: "Select an option",
allowClear: true
});
// Other logic pertaining to this select also goes here.
}
}
}
// Primary component.
var MainComponent = {
controller: function() {
var ctrl = this;
//...