By Guillaume Briday
$("#my-button").click(function () {
const name = $("#city-select").val()
$.ajax({
url: `/my/awesome/api?name=${name}`,
done (data) {
const div = $("
")
data.forEach((item) => {
div.append(`${item.name} `)
})
$("#my-content").html(div)
}
})
})
def create
@user = User.new(params[:user])
respond_to do |format|
if @user.save
format.html { ... }
format.js
else
format.html { ... }
format.js
end
end
end
// app/views/users/create.js.erb
const users = document.querySelector("#users");
users.insertAdjacentHTML("beforeend", "<%= j render(@user) %>");
It was cool but...
import { useState } from 'react'
function MyComponent() {
const [name, setName] = useState('')
const [items, setItems] = useState([])
useEffect(() => {
fetch(`/my/awesome/api?name=${name}`)
.then(res => res.json())
.then((data) => {
setItems(data)
})
}, [name])
return (
...
{items.map(item => (
-
{item.name}
))}
)
}
From manipulating DOM with jQuery to manipulate Data with React.
Maybe you just need Turbo with Stimulus...
And https://www.stimulus-components.com/ π
<%# app/views/todos/show.html.erb %>
My awesome todo
<%= turbo_frame_tag @todo do %>
<%= @todo.name %>
<%= @todo.description %>
<%= link_to 'Edit this todo', edit_todo_path(@todo) %>
<% end %>
<%# app/views/todos/edit.html.erb %>
Editing message
<%= turbo_frame_tag @todo do %>
<%# form_with ... %>
<% end %>
class CommentsController < ApplicationController
def index
budget = Budget.find(params[:budget_id])
render partial: 'comments/comments', locals: { comments: budget.comments }
end
end
<%= turbo_frame_tag :comments, src: comments_path(budget_id: @budget.id), loading: 'lazy' do
<%# Adding a nice loader that will be replaced once the partial gets loaded. %>
<% end %>
What if you need to update multiple frames at once
Or update frames from HTTP responses?
<%# app/views/todos/show.html.erb %>
<%= turbo_stream_from @todo %>
<%= @todo.name %>
class Todo < ApplicationRecord
# broadcasts
after_create_commit -> { broadcast_append_to self }
after_destroy_commit -> { broadcast_remove_to self }
after_update_commit -> { broadcast_replace_to self }
end