The Problem:
A user is utilizing Hotwire (Stimulus/Turbo/Rails) to implement a user search functionality in a Rails application. The user wants to dynamically update a specific TurboFrame when a search is performed, but the current approach using Stimulus isn’t triggering the redrawing of the TurboFrame. The user seeks guidance on the correct method to reload and redraw a TurboFrame after the initial rendering.
The Solutions:
Solution 1: Reload with Stimulus/Turbo/Rails
To update a Turboframe and redraw it after the initial load, follow these steps:
- In the Stimulus controller, use the
reload()
method on the frame element. This will reload the frame from its current source:
reload() {
this.element.reload();
}
- Use the
data-controller
anddata-action
attributes to connect the Stimulus controller to the frame:
<%= turbo_frame_tag :reloadable, src: request.url,
data: {
controller: "hello",
action: "click->hello#reload"
}
%>
- For the search form, use
data-turbo-frame
to specify the frame that should be updated when the form is submitted:
<%= form_with url: "/users", method: :get,
data: {turbo_frame: :users} do |f| %>
...
<% end %>
- In the view that renders the frame’s content, update the scope of the data displayed based on the form parameters:
<%
scope = User.all
scope = scope.where(name: params[:name]) if params[:name].present?
@users = scope
%>
By following these steps, you can use Stimulus and Turbo to dynamically reload and update Turboframes based on user interactions or form submissions.
Solution 2: Setting Default Title
According to the Hotwire documentation, removing the loaded
attribute of the <turbo-frame>
DOM element will trigger the reloading action using the path specified in the src
attribute. This can be easily achieved through Stimulus:
reload() {
const {src: src} = this;
this.removeAttribute('loaded');
this.src = src;
}
Q&A
How do you reload a specific turbo frame after it’s rendered the first time?
You need some instance variables in that show
action or render locals: {..
and this
refers to a controller instance.
How does Hotwire manage routing?
Using data-turbo-frame
on html element triggers Hotwire to handle the route.
Video Explanation:
The following video, titled "Hotwire Tutorial: Inline Editing Using Turbo Frames - YouTube", provides additional insights and in-depth exploration related to the topics discussed in this post.
Turbo Frames allow you to dynamically update sections on the page in response to some action, such as clicking a link or submitting a form.
The following video, titled "Hotwire Tutorial: Inline Editing Using Turbo Frames - YouTube", provides additional insights and in-depth exploration related to the topics discussed in this post.
Turbo Frames allow you to dynamically update sections on the page in response to some action, such as clicking a link or submitting a form.