Turbo Frames - Typeahead Search

Update filter results using eager loading Turbo Frames.

View Solution on Patreon
Turbo Frames - Typeahead Search

Premise

One of the primary benefits of using Turbo Frames is view decomposition. A case where this comes in especially handy is when you update parts of your view reactively to user input. A common scenario where this happens is in typeahead search.

Challenge

The foundational component of this challenge is a turbo frame which lists a set of books. To emulate a database call, I’ve added a simple JSON file containing popular science fiction writings:

https://stackblitz.com/edit/turbo-frames-typeahead-search?file=app.js,index.html,index.js,books.json

To avoid having to code an entire CRUD backend, I’ve added a simple route that filters those books based on the input query, and throws together a Turbo Frame containing the results:

https://stackblitz.com/edit/turbo-frames-typeahead-search?file=app.js,index.html,index.js%3AL31

You can dive into the JavaScript if you like, but it boils down to a list of books containing the query either in the author, title, or year attribute.

Our main view includes a Turbo Frame with a matching ID:

https://stackblitz.com/edit/turbo-frames-typeahead-search?file=app.js,index.html%3AL49

Your challenge is to connect the backend search algorithm to this Turbo Frame so that the filtering is triggered whenever a user enters a query in this input:

https://stackblitz.com/edit/turbo-frames-typeahead-search?file=app.js,index.html%3AL44

Please add your code here:

As a bonus, you could wrap every occurrence of the query string in <em></em>, thus highlighting it. Do that without altering the server-side code! This is how the end result should look like:

Typeahead Search of a List of Books

Caveats

  • When setting the Turbo Frame’s src attribute, be sure to use only URL safe characters!
  • To inject the highlight tags, you can make use of Turbo Frame render pause/resuming

Teaser

When adding this to your own app, don’t forget to add client-side debouncing to the keyup event!

More from

Turbo Frames - Swiper with Autoplay and View Transitions
14 January 2025

Create an autoplaying swiper using view transitions and Turbo Frames

Faceted Search with Stimulus and Turbo Frames
10 December 2024

Harness the power of Stimulus and Turbo Frames to drive a simple but powerful faceted search solution

Turbo Frames - Markdown Preview
08 October 2024

Typeahead previews of markdown by simple Turbo Frame rerendering

Cookies
essential