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
11
12
13
14
15
16
import { Controller } from '@hotwired/stimulus';

export default class extends Controller {
  static targets = ['toggleable'];
  static classes = ['toggle']

  toggle() {
    this.toggleableTargets.forEach((t) => t.classList.toggle(this.toggleClass));
  }

  hide(event) {
    if (this.element.contains(event.target) === false) {
      this.toggleableTargets.forEach((t) => t.classList.add(this.toggleClass));
    }
  }
}