Morphing With Turbo Streams

Turbo Streams provide a real-time, server-driven way to update Rails applications without complex JavaScript. One of the latest enhancements to Turbo Streams is the ability to use the method: :morph option in various actions, allowing more efficient DOM updates. This option can be used with actions like update, replace, and others, providing more control over how updates are applied.

What is Morphing?

Morphing refers to updating only the changed parts of a DOM element rather than fully replacing it. This helps preserve the state of interactive elements—like form inputs, scroll positions, or event listeners—providing a smoother user experience and improving performance.

Using the method: :morph Option

With the new method: option, you can specify morphing in any Turbo Stream action where partial or incremental updates are required. Here’s an example:

1
2
# app/views/comments/update.turbo_stream.erb
<%= turbo_stream.replace dom_id(@comment), @comment, method: :morph %>

By adding method: :morph, only the differences between the current and new content are applied, minimizing disruption to the UI.

When to Use Morphing

Morphing is ideal when:

Turbo Stream morphing offers a more efficient way to update views dynamically by allowing you to fine-tune how DOM updates are applied. Whether you’re updating forms or handling real-time data, the method: :morph option helps you maintain a smooth, performant user experience with minimal disruption.