In part one of this series, we used Hotwire's Stimulus and Turbo Frames to present modals in Rails.
Now, we'll dive into another method we can use to present modals: Turbo Streams.
What Are Turbo Streams in Ruby on Rails?
Turbo Streams is a subset of Turbo. It allows us to make fine-grained, targeted updates to a page. By default, it contains seven CRUD actions, but we're free to add more actions within our applications.
Now, we'll create a show_remote_modal
action which renders and presents the <dialog>
from our previous post.
Creating a Custom Action
Create a folder to place all custom Stream Actions in:
And a file for the Action:
Import the Stream Actions into the application:
If you're using import maps, you'll need to update the config and restart the server:
Change the global remote modal container to an HTML element instead of a Turbo Frame:
The custom Stream Action can be implemented as:
In the above snippet, this
refers to StreamElement
, which is the custom element underpinning <turbo-stream>
. The templateContent
getter is defined by this element.
Using the Action with a Rails Helper
Since this is a custom Action, we'll need to manually create a Rails helper to use it.
We can now use this helper in our views.
Remember to remove the data-controller
attribute: we don't need it anymore. In fact, we can delete the controller itself.
We'll also need to change the template's name so it renders as a Turbo Stream.
Turbo Streams are disabled by default for GET
requests, so we'll need to manually enable them for the link:
Refresh the page and click Show contact form. It should still work as before, but now it's rendered using a custom Stream Action!
Wrapping Up
In this two-part series, we explored three different methods to present modals using Hotwire: Stimulus, Turbo Frames, and Turbo Streams. More importantly, the modals were presented with accessibility as the main consideration.
The web should be usable by everyone and it's important for us, as web developers, to put in the effort to make websites accessible.
Basecamp's accessibility guide is publicly available and a fantastic resource to learn the ropes.
I also recommend checking out the docs for Stimulus and Turbo to familiarise yourself with all their features and the APIs used in this series.
Happy coding!
P.S. If you'd like to read Ruby Magic posts as soon as they get off the press, subscribe to our Ruby Magic newsletter and never miss a single post!