#13 Turbo Streams: 5 ways to render View Components
If you have problems rendering a ViewComponent with Turbo Streams, here are some solutions.
4 ways to do it in a controller: #
render_to_string(PaginationComponent.new(results: @results))
view_context.render(PaginationComponent.new(results: @results))
PaginationComponent.new(results: @results).render_in(view_context)
# most universal:
ApplicationController.render(PaginationComponent.new(results: @results), layout: false)
All work, use either one with Turbo Streams:
# app/controllers/hello_controller.rb
def some_action
respond_to do |format|
format.turbo_stream do
render turbo_stream: [
# turbo_stream.update('inboxes-pagination', render_to_string(PaginationComponent.new(results: @results))),
# turbo_stream.update("inboxes-pagination", view_context.render(PaginationComponent.new(results: @results))),
turbo_stream.update("inboxes-pagination", PaginationComponent.new(results: @results).render_in(view_context))
]
end
end
end
Our just use a some_action.turbo_stream.erb
template: #
# app/controllers/hello_controller.rb
def some_action
respond_to do |format|
format.turbo_stream
end
end
# index.turbo_stream.erb
<%= turbo_stream.update "inventory-pagination" do %>
<%= render PaginationComponent.new(results: @results) %>
<% end %>
That’s it!
Did you like this article? Did it save you some time?