User Live Search with Stimulus, Turbo Frames and PgSearch

Curated ago by @jeremysmithco

Description

Here’s a solution I’ve used on a project to add a user switcher dropdown with typeahead search to a navbar. It uses the pg_search gem for Postgres full-text search.

There are a lot of blog posts out there with similar solutions, with terms like: typeahead, autocomplete, autosuggest, instant search.

1
2
3
4
5
6
7
8
9
10
<%= tag.div(class: "mr-2 relative", data: { controller: "toggle", toggle_toggle_class: "hidden" }) do %>
  <%= tag.button(class: "flex space-x-1 items-center cursor-pointer rounded rounded-b-none py-2 px-3 border-b border-transparent hover:bg-gray-100 hover:border-gray-200", data: { action: "click->toggle#toggle click@window->toggle#hide pagehide@window->toggle#hide" }) do %>
      <%= tag.span(user.full_name, class: "text-lg font-semibold max-w-xs truncate") %>
      <%= tag.span(class: "fa fa-caret-down text-blue-500") %>
  <% end %>

  <%= tag.div(class: "hidden z-40 origin-top-right absolute left-0 mt-1 w-60 rounded border border-gray-300 shadow-lg p-2 bg-white", data: { toggle_target: "toggleable" }) do %>
    <%= render partial: "users_searches/form" %>
  <% end %>
<% end %>

This switcher dropdown might be loaded within a navbar.