Orginally published at Medium on Feb 21st 2020.
Learn how to set-up a search autocomplete with Stimulus. A user can see query results after typing in the input field. The Stimulus Autocomplete library is a Stimulus controller that provides an easy solution to auto-completion.
- Install package
- Import library
- Add-basic-HTML-layout
- Create route
- Create controller method
- Create results view
Before you start
Make sure you have Stimulus installed. Check the package.json file or run yarn why stimulus
. If Stimulus is not yet installed, follow the documentation.
1. Install package
Add stimulus autocomplete to your project:
yarn add stimulus-autocomplete
2. Import library
Add to the index.js file
import { Application } from "stimulus"
import { Autocomplete } from "stimulus-autocomplete"
const application = Application.start()
application.register("autocomplete", Autocomplete)
3. Add basic HTML layout
<div class="max-w-xs mx auto bg-white">
<div data-controller="autocomplete" data-autocomplete-url-value="/autocomplete">
<input type="text" class="w-full" data-autocomplete-target="input" placeholder="Type to search..."/>
<ul data-autocomplete-target="results"></ul>
</div>
</div>
Let’s add a wrapper around to narrow the input field and search results.
-
data-controller=”autocomplete"
scopes the imported controller to the div -
data-autocomplete-url-value
sets the route to get the search results from -
data-autocomplete-target=”input”
listens for a keyboard change and reads the input field -
data-autocomplete-target=”results”
is the wrapper to inject the result list items in
4. Create route
get '/autocomplete' , to: 'products#autocomplete'
Fetch the HTML search results that should be displayed at the user types
5. Create controller method
def autocomplete
@search_results = ["apple", "apple juice", "apple compote"]
render layout: false
end
Layout false ensures that only plain HTML is returned. The header and metadata are not included. Precisely what is needed as the search results should display text only.
6. Create results view
<% @search_results.each do |result| %>
<li role="option"><%= result %></li>
<% end %>
Display the search results in a HTML view that matches the created route
products/_autocomplete.html.erb
Conclusion
Stimulus proves it value by sprinkling JavaScript on the page, without the need for much custom JavaScript. Leverage pre-build components and suddenly developers can easily bring interactivity to HTML-dominant web applications.
Top comments (3)
Thank you for your tutorial, really easy to go through!
Just for information, with Rails 6, I had to change the
render layout: false
byrender partial: 'partial_name', formats: :html
this doesn't work, it doesn't filter the data.
the serverside has to filter the data based on query parameters