Skip to content

Instantly share code, notes, and snippets.

@dbridges
Created February 25, 2020 16:08
Show Gist options
  • Save dbridges/3eb95175c6ae504de12d2d0a24117182 to your computer and use it in GitHub Desktop.
Save dbridges/3eb95175c6ae504de12d2d0a24117182 to your computer and use it in GitHub Desktop.
<ul class="food">
<% items.each do |item| %>
<li>
<span><%= item.name %></span>
<span class="kind"><%= item.kind %></span>
</li>
<% end %>
</ul>
import { Controller } from "stimulus";
import axios from "axios";
export default class extends Controller {
static targets = ["food"];
connect() {
console.log("connected");
}
async filter(event) {
const kinds = [...event.target.selectedOptions].map(opt => opt.value);
const newFood = await axios.get("/food", { params: { kinds } });
this.foodTarget.innerHTML = newFood.data;
}
}
class FoodController < ApplicationController
def index
@food = Food.where(kind: params[:kinds])
render partial: "food", locals: { items: @food }
end
end
class HomeController < ApplicationController
def index
@food = Food.where(kind: "fruit")
end
end
<h1>Rails + Stimulus + React</h1>
<div data-controller="food">
<%= select_tag "kinds",
options_for_select(Food.kinds.keys, "fruit"),
multiple: true,
data: { action: "change->food#filter" } %>
<div data-target="food.food">
<%= render "food/food", items: @food %>
</div>
</div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment