0
0
Ruby on Railsframework~5 mins

Stimulus and Turbo (Hotwire) in Ruby on Rails

Choose your learning style9 modes available
Introduction

Stimulus and Turbo help you build fast, interactive web pages without writing much JavaScript. They make your app feel quick and smooth by updating parts of the page automatically.

You want to add simple interactivity like button clicks or form handling without full page reloads.
You want to update parts of a page dynamically after a user action, like submitting a form or clicking a link.
You want to speed up your Rails app by avoiding full page refreshes and loading only what changes.
You want to keep your JavaScript code organized and easy to maintain.
You want to build modern web apps with less JavaScript and more server-driven HTML.
Syntax
Ruby on Rails
import { Controller } from "@hotwired/stimulus"

export default class extends Controller {
  connect() {
    // code to run when controller connects
  }

  someAction(event) {
    // code to run on event
  }
}

Stimulus controllers are small JavaScript classes that connect to HTML elements using data attributes.

Turbo uses special HTML attributes and server responses to update page parts without full reloads.

Examples
This Stimulus controller shows an alert when the button is clicked.
Ruby on Rails
<button data-action="click->hello#greet">Click me</button>

// hello_controller.js
import { Controller } from "@hotwired/stimulus"

export default class extends Controller {
  greet() {
    alert('Hello!')
  }
}
This Turbo Frame loads the post content inside the frame without reloading the whole page.
Ruby on Rails
<a href="/posts/1" data-turbo-frame="post_frame">View Post</a>

<div id="post_frame" data-turbo-frame>
  <!-- Post content loads here -->
</div>
This form submits via Turbo, updating the page dynamically without a full reload.
Ruby on Rails
<form action="/comments" method="post" data-turbo="true">
  <input name="comment" />
  <button type="submit">Submit</button>
</form>
Sample Program

This example shows a button that triggers a Stimulus controller action to display an alert message when clicked.

Ruby on Rails
<!-- index.html.erb -->
<div data-controller="hello">
  <button data-action="click->hello#greet">Say Hello</button>
</div>

// hello_controller.js
import { Controller } from "@hotwired/stimulus"

export default class extends Controller {
  greet() {
    alert('Hello from Stimulus!')
  }
}
OutputSuccess
Important Notes

Always add data-controller to the HTML element you want Stimulus to manage.

Turbo Frames let you update only parts of the page, making apps faster and smoother.

Use data-action to connect user events like clicks to Stimulus controller methods.

Summary

Stimulus adds simple JavaScript behavior to HTML using controllers and data attributes.

Turbo speeds up page updates by replacing only parts of the page without full reloads.

Together, they help build fast, interactive Rails apps with less JavaScript code.