Search⌘ K

Adding Our First Controller

Explore how to add your first Stimulus controller to manage interactive elements like toggling content visibility. Understand attaching controllers to DOM elements, defining the connect method in TypeScript, and how Stimulus handles multiple controllers and dynamic DOM updates. This lesson prepares you to enhance front-end interactivity in Rails applications.

How controllers work

The first thing we’re going to do with Stimulus is, create a “Show/Hide” button that will toggle the contents of the favorite concerts block on our page.

The bulk of our Stimulus code will go into a controller. Similar to our Rails controller, a Stimulus controller is where we store responses to events. But, Stimulus controllers are different in that they have less structure and fewer expectations than a Rails controller.

To invoke a controller, we add an attribute named data-controller to a DOM element on our page. The value of the attribute is the name of the controller. If we add an attribute data-controller="toggle", then Stimulus attaches it to a ToggleController, which it expects will be at controllers/toggle_controller.ts (or .js).

If the controller’s name is more than one word, we use dash case, so it would be fancy-color, not fancyColor. The controller has the same scope as the DOM element it’s attached to. This means that any events we ...