💡

Fast and easy SPAs in Rails, thanks to Hotwire

Hotwire Turbo Ruby on Rails

In Hotwire, with the combination of Turbo Frames and Turbo Stream formats, we can perform precise operations on pieces of our web pages without having to write a single line of JavaScript. Compared to using a frontend library like React, there is no state to manage, no complex actions to dispatch, no reducers... Turbo is a joy to work with!

Hotwire is the commercial name that bundles two JS based technologies aiming to simplify the development of reactive web apps : Turbo Frame and Turbo Streams. It is an evolution of Rails previous technology Turbolinks, and it offers an alternative approach to building modern web applications without using much JavaScript by sending HTML instead of JSON over the wire.

Hotwire's documentation is back-end agnostic, so I found it to be VERY unpleasant and uninteresting to read at first. But by experimenting a few of its core features for a simple demo page, I was really impressed at the simplicity it offers. Compared to using a frontend library like React, there is no state to manage, no complex actions to dispatch, no reducers... For the simplest actions, you just wrap your components into frames, make sure they have matching IDs, and you have an SPA-like experience. Turbo is a joy to work with!

Turboframes

Basic updating mechanism

When clicking on a link within a turbo frame, Turbo expects a frame of the same id on the target page.

Turbo will then replace the content of the turbo frame of the source page with the content of the turbo frame of the target page.

If turbo doesn't find the same id in the target page, it will remove the content and log an error.

1.png

Updating with an indirect target

A link can target a turbo frame that is not directly nested in the source turbo frame, thanks to the data-turbo-frame attribute. In that case, the turbo freame on the target with the same id as the data-turbo-frame attribute will be used to replace the turbo frame with the same id in the target page.

2.png

Updating with a full page replacement

Sometimes, you want to completely replace a screen, and not just a component. Putting "_top" as the data-turbo-frame attirbute replaces the whole page with the target page.

When using the "_top" keyword, the URL of the page changes to the URL of the target page, which is another difference from when using a regular Turbo Frame.

3.png

Turbo streams

There a few cons with turbo frames, and that is why we need turbo streams:

  1. You can only update one frame at a time
  2. If you use _top on parallel actions, they will all be affected by the page replacement, which can be inconvenient
  3. Turbo frames can only update content

→ Let's get in touch

Got questions or feedback about this article? Interested in discussing your project? I'm all ears and always open to new opportunities. Shoot me an email and tell me what you have in mind.