Introduction

In this post I will cover the process of adding searchable dropdown boxes to your Lucky webapp with the Select2 Javascript library and styling them with Bootstrap 5.

Software

The following software versions were used in this post.

  • Lucky - 0.28.0
  • Select2 - 4.1.0-rc.0
  • Bootstrap - 5.1.0

Note

I will be disabling turbolinks otherwise the dropdown does not load correctly on subsequent page visits.

Installation

From the terminal add the required packages with Yarn and remove turbolinks.

cmd

yarn add select2
yarn add jquery
yarn add select2-bootstrap-5-theme
yarn remove turbolinks
    

Setup

Import and configure Select2 into the src/js/app.js file and disable turbolinks.

file

// src/js/app.js
// Delete the turbolinks line
// require("turbolinks").start();
// ...
import "select2/dist/js/select2";
// ...  
$(document).ready(function () {
  // "content-search" is the CSS class name used by Select2
  $('.content-search').select2({ 
    theme: "bootstrap-5",
  });
});
    

Import the SCSS into the src/css/app.scss file.

file

// src/css/app.scss
@import "select2/src/scss/core";
@import "select2-bootstrap-5-theme/src/include-all";
    

Usage

Apply the content-search CSS class to dropdowns you would like to use Select2.

file

div class: "mb-3" do
  label_for(operation.vrf_id, "VRF", class: "form-label")
  select_input(operation.vrf_id, class: "form-control content-search") do
    options_for_select(operation.vrf_id, options_for_vrfs)
  end
end
    

And that's all there is to it, if everything is setup correctly, your dropdowns will now have a search box.

Deprecation Warnings

After installing the select2-bootstrap-5-theme I was getting some deprecation warnings from Dart related to division.

To work around this, update the webpack.mix.js file to silence the warnings.

file

// webpack.mix.js
// Change this line
// .sass("src/css/app.scss", "css"
.sass("src/css/app.scss", "css", {
  sassOptions: {
    quietDeps: true,
  },
})
    

Summary

In this post we installed and configured the Select2 Javascript library, while also adding Bootstrap 5 styling to our dropdowns in a Lucky webapp.

Tags

lucky crystal select2 bootstrap