- Published
- Author
- Nived HariSystem Analyst
"Search-as-You-Type" in Rails with Turbo Frames and Stimulus
Making the search box more interactive can be achieved with simple steps:
We could do this without Turbo by submitting the form whenever an input event occurs, right? No. In that case, on each input, the form gets submitted, and the input field loses focus. This is where Turbo Frames come into play. For this scenario, we need Turbo to reload only the content we want to update while leaving the rest of the page as it is.
For this, we define which part we want to reload based on our search by wrapping that particular section inside a
Sample search form:
Example:
( We will give data : { turbo_frame: "search_results" } in this case )
In this way, when a fetch occurs from the search form, only the part inside the
For optimization, we can add debouncing also, which can be done in the Stimulus controller.
#RubyOnRails #turbo #turbo_frames
Making the search box more interactive can be achieved with simple steps:
We could do this without Turbo by submitting the form whenever an input event occurs, right? No. In that case, on each input, the form gets submitted, and the input field loses focus. This is where Turbo Frames come into play. For this scenario, we need Turbo to reload only the content we want to update while leaving the rest of the page as it is.
For this, we define which part we want to reload based on our search by wrapping that particular section inside a
turbo_frame_tag and targeting that Turbo Frame from the search form.Sample search form:
Code
<%= form_with(
url: search_path, method: :get,
data: { turbo_frame: "frame_id", turbo_action: "advance", controller: "search", action: "input->search#submit" }
) do |f| %>
<%= f.search_field field_name, placeholder: placeholder, value: params %>
<% end %>turbo_frame : Points to the specific Turbo Frame we want to update with the search results. It allows us to reload only the content within this frame without affecting the rest of the page.turbo_action : Defines the behavior of the Turbo request. In this case, it is set to "advance," which means the URL is appended to the previous ones. This allows users to navigate back to previous searches using the browser's back button, maintaining the search history. There are other actions like "restore", "pop" as well.Example:
Code
<%= turbo_frame_tag "search_results" do %>
#This will contain the search results
<% end %>( We will give data : { turbo_frame: "search_results" } in this case )
In this way, when a fetch occurs from the search form, only the part inside the
turbo_frame_tag is reloaded. The rest of the page remains untouched, and the form won't lose focus.For optimization, we can add debouncing also, which can be done in the Stimulus controller.
#RubyOnRails #turbo #turbo_frames