How to use Hotwire in Rails?
Hotwire is an innovative approach to building modern web applications without much JavaScript by sending HTML instead of JSON over the wire. It consists of TurboDrive, TurboFrames, TurboStreams, and Stimulus. Integrating Hotwire into a Rails application can make it more interactive without the weight of a full-blown frontend framework. Here’s a concise guide to getting started:
- Installation: First, add the `hotwire-rails` gem to your Gemfile:
```ruby gem 'hotwire-rails' ```
Then, run `bundle install` to install the gem. After that, run `rails hotwire:install` to set up Hotwire with Stimulus.
- TurboDrive: TurboDrive speeds up navigation between pages by only replacing the `<body>` content. You don’t need to do anything extra; once installed, it’ll automatically speed up page transitions.
- TurboFrames: TurboFrames allows for parts of a page to be fetched and replaced without a full-page reload. Wrap a section of your HTML in a `turbo-frame` tag with a unique `id`:
```html <turbo-frame id="frame_id"> <!-- Content to be replaced goes here --> </turbo-frame> ```
When you link to a URL, if the response contains a TurboFrame with the same `id`, only that frame’s content will be replaced.
- TurboStreams: TurboStreams offers a way to push asynchronous updates to the client. You can create TurboStream templates in Rails to specify how parts of the page should be modified:
```html <turbo-stream action="replace" target="frame_id"> <template> <!-- New content goes here --> </template> </turbo-stream> ```
- Stimulus: While Hotwire minimizes the need for custom JavaScript, sometimes it’s necessary. Stimulus is a lightweight framework included with Hotwire to aid with this. Define controllers, actions, and targets to make managing your custom JS easier.
- Integrate with WebSockets: Combine Hotwire with Action Cable to push updates from the server to the client in real-time. This way, you can reflect changes instantly without a manual refresh.
Hotwire offers an exciting blend of minimal JavaScript with the robustness of Rails. It’s about enhancing the existing Rails way of building web applications rather than replacing it. For detailed examples and advanced configurations, refer to the official Hotwire documentation.