Rendering content based on filter?

Currently i have a filter which hides and shows divs (using CSS & JS) based on data attributes matching the filter. Is there a way to use stimulus to just render the elements that match the filters?filters

I recently built a similar filtering feature with Rails. I don’t know your exact requirements, but you might consider filtering results server-side and returning the rendered matches instead of using Javascript. Your feature could be a lot easier to build that way.

But if you’re loading all of the results on initial page load and happy with filtering from there, then you could store the filters’ values somewhere (e.g. a global javscript variable) and trigger an event anytime a filter is updated.

Then each result (trip) can be hooked up to a Stimulus controller that listens to that event and toggles the element depending on whether the trip matches the filters.

The HTML might look like this:

<article class="trip" data-controller="trip" data-trip-price="...">...</article>

And the accompanying Stimulus controller (trip_controller.js):

import { Controller } from "stimulus"

export default class extends Controller {
  connect() {
    window.addEventListener("filter-update", this.toggle)

  toggle = () => {
    if (this.matchesFilters()) { = ""
    } else { = "none"

  matchesFilters() {
    // filter matching logic here

I’m doing something similar to show/hide the columns in a table based on the person’s choice of what columns to display.

Hope this helps.

Thanks @smidwap
That is what i am currently doing but in vanilla javascript(display:none), but was curious if using stimulus can help me do something like a state change?

Check out the Managing State chapter in the Stimulus Handbook. From my experience, Stimulus doesn’t do a lot of magic out-of-the-box like respond to state change. Where Stimulus has been a big help is turning my spaghetti code into more comprehensible and flexible components (controllers) with little to no learning curve.

1 Like