Skip to main content
Published in Engineering Insights

Two Tips for Reusable UI with Stimulus

Two Tips for Reusable UI with Stimulus
Table of contents
  1. Overview
  2. Reusable Components
    1. The Problem with Outlets (and a Solution)
    2. The Problem with Events (and a Solution)
  3. Outlets, targets or events: which should a reusable component use?
    1. How do you wire an outlet when one fits?
  4. Seven rules for reusable Stimulus controllers
  5. How do reusable controllers behave across Turbo page visits?
  6. Conclusion

Here are two issues we ran into implementing a library of reusable UI components in Stimulus, and how we worked around them by rethinking our approach to outlets, targets and events.

Overview#

For those new to the framework, Stimulus controllers are lightweight JS objects attached to DOM elements. They are descendants of Controller, which is exported by @hotwired/stimulus, and associated with elements by setting the data-controller attribute to the controller’s identifier, e.g.:

HTML
<div id="counter" data-controller="counter" />
JavaScript
export default class CounterController extends Controller {
  ...
}

All else equal, Stimulus assumes a controller’s class is enough information to identify it on the page and interact with it. Outlets, Stimulus’ primary mechanism for controllers to access other controllers, are identified by their class. Consider the following example from the Stimulus documentation:

JavaScript
export default class ChatController extends Controller {
 static outlets = [ "user-status" ]

 connect () {
   this.userStatusOutlets.forEach(status => ...)
 }
}

The elements containing the controllers will be identified in the DOM via data-chat-user-status-outlet attributes whose value can be any CSS selector you like, but once those elements have been identified, they will be expected to have a UserStatusController. Note that the controller class is encoded in the attribute name. From the documentation: “Stimulus will throw an exception if you try to declare an element as an outlet which doesn’t have a corresponding data-controller and identifier on it.”

Consider further the case of custom events, emitted by controllers with dispatch. These are like click and blur, but user-defined, and they can carry structured data payloads. Custom events have prefixes that allow them to be namespaced, so you can tell the difference between, say, a confirm event sent from a form footer versus one sent from a modal. By default, the prefix of a custom event is the name of the controller that emits it, slightly transformed: ModalController will emit modal:confirm, while FormFooterController will emit form-footer:confirm. In order to consume those events, you’d bind them in the DOM with a data-action attribute:

HTML
<div ... data-action="form-footer:confirm@window->confetti#blast" ... />

This makes sense in the case of footers and modals, because there’s usually only one of those things on any given page. If there were more than one though, ConfettiController wouldn’t be able to tell them apart.

Reusable Components#

Because there’s usually only one, the class name of a modal or a footer can identify both what the component is and what it means in the application. When components are intended to be reused, this is no longer the case, because the class becomes generic, like SelectController. Suppose you have such a component that represents a custom select box. Two requirements:

  • You want this to be the standard select box for your application, so there will be cases where you call it multiple times on a single page
  • Part of the custom behavior is that it can be initialized, set, cleared, labeled, and so on by other components
Dropdown with a Pick one search field and options Hello World, Hi World, Yo, World! and Greetings and Salutations, O World
A fancy select component from the Ant Design UI library

The Problem with Outlets (and a Solution)#

Class names like SelectController still identify what the component is, but no longer identify its meaning. Imagine a contact form with multiple select boxes. One is for (say) country, another for states and provinces, another is for the contact’s gender, and so on. 

Having encountered this situation in the wild, I found it wasn’t very useful to address all of the select boxes in the form, because they had nothing in common past the UI element. That’s the state of things with outlets, though: Because outlets are identified by their class, to control a particular select box with an outlet, a controller would have to poll all of the select boxes on the page and then filter them by some other means. It also breaks encapsulation by forcing callers to know the concrete UI element of their target (a select box) rather than its meaning in the application (country, states and provinces, contact gender).

Suppose our form populates the states and provinces box dynamically when the user selects a country. This is handled by a higher level controller, say, ContactFormController. In Stimulus, the primary difference between targets and outlets is that targets relate controllers to DOM elements, while outlets relate them to other controllers. Where outlets must be identified by their class, targets are identified by arbitrary names in DOM attributes, so we can simply flag the state-and-province select as a target like so:

HTML
<div data-controller="select" data-contact-form-target="statesAndProvinces" ... />

Now we know where on the page to send the update. The problem now is that the target is a DOM element, rather than the SelectController. This is why outlets require their class to be known: Even if you have it narrowed down to a single element, Stimulus needs to know which controller loaded on that object you want to call.

What happens next probably depends on your components. In our case, we were wrapping React components with Stimulus controllers, so we wanted higher level controllers like ContactFormController to be able to reinitialize those components with new props. The Stimulus controllers wrapping the React components all inherited from a common base class, ComponentController, which set a listener for a custom update event. Callers like ContactFormController could then identify the component’s element as a target, and dispatch an update event on it with the new props as a payload.

A Brief Digression on Hierarchy

The other difference between outlets and targets is that target elements must fall under their controller’s element in the DOM hierarchy, while outlets can be anywhere on the page. If you use the approach above, the higher level controller must be defined on an element that encompasses all of the components that depend on it.

If this is a problem, components with no common roots can be coordinated with events, (see below), but a better first approach might be to put something like ContactFormController near the top of the hierarchy, rather than on the form element itself.

The Problem with Events (and a Solution)#

The other problem is how you consume events emitted by these controllers. When the user makes a selection, the SelectController on the country input will (let’s say) announce its new value with a custom event. How do you bind it?

HTML
<div data-controller="contact-form" data-action="select:change->contact-form#updateStatesAndProvinces">

This method will be called whenever a select box in the form is used. We could check some value in the payload once the method is called, but like polling all outlets of a given type to find the right one, that gives us the ick. We should be able to use data-action more selectively than that. What we want is more like this:

HTML
data-action="country:select->contact-form#updateStatesAndProvinces"

Instead of using the prefix to identify the class that emitted the event, it becomes a sort of channel name that can be used to connect arbitrary controllers anywhere on the page. (Add @window to the event name to listen for events emitted outside of the controller’s hierarchy.) We can then specify this value when invoking the component, which in our case was done by rendering a partial:

ERB
<!-- app/views/contacts/_form.html.erb -->	
<%= render "components/select", channel: "country", props: ... %>
<%= render "components/select", channel: "states-and-provinces", props: ... %>

The partial passes the value into the component controller:

ERB
<!-- app/views/components/_select.html.erb -->
<div data-controller="select" data-select-channel-value=<%= channel %> ... %>

Then, when implementing your components, you can override the default prefix when you call dispatch:

JavaScript
// in SelectController, on user selection
dispatch("select", prefix: channelValue, detail: { ... })

Outlets, targets or events: which should a reusable component use?#

Use a target when a parent controller owns the component and the component sits inside the parent's element. Use a custom event with a channel prefix when several instances announce changes and the listener must tell them apart. Add @window when the listener sits outside their hierarchy. Use an outlet when the controller's class says what the component means. That is rarely true of a reusable select box or date picker.

MechanismWhat it points atHow the caller finds itWhere it can liveBest fit for reusable UI
TargetsA DOM elementAny name you choose, in a data-[controller]-target attributeInside the controller's elementA parent controller that sets or updates one specific instance
Custom eventsWhoever binds it in data-actionThe event name and its prefix, in a data-action attributeAnywhere, with @window outside the hierarchyInstances that announce changes to listeners they do not know about
OutletsAnother controllerThe controller identifier plus a CSS selectorAnywhere in the documentOne-of-a-kind controllers whose class says what they mean, like a modal

This is why the contact form above uses targets and events. Every select box on it is a SelectController. An outlet would tie the form to that class and a CSS selector, while a target name or a channel prefix names each box by its job, like country or statesAndProvinces.

How do you wire an outlet when one fits?#

Give the host controller's element a data-[identifier]-[outlet]-outlet attribute set to a CSS selector for the other controller's elements. List that controller's identifier in static outlets. Stimulus then adds [name]Outlet, which throws when nothing matches, and has[Name]Outlet to check first.

Here the contact-form controller's element gets data-contact-form-modal-outlet="#confirm-modal". The modal elsewhere on the page has id="confirm-modal", data-controller="modal" and hidden. A type="button" button in the form has data-action="contact-form#confirm".

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

export default class extends Controller {
  open() {
    this.element.hidden = false
  }
}
JavaScript
// contact_form_controller.js
import { Controller } from "@hotwired/stimulus"

export default class extends Controller {
  static outlets = [ "modal" ]

  confirm() {
    if (this.hasModalOutlet) this.modalOutlet.open()
  }
}

A modal fits an outlet because the page has one. The Gnar Company's post React in Rails, One Component at a Time skips outlets. Its ComponentController base class takes this job: “Add an event listener to allow other entities on the page to update the component with new full or partial props (see “Two Tips for Reusable UI With Stimulus” for why we don’t use a Stimulus outlet here)”.

Seven rules for reusable Stimulus controllers#

A reusable Stimulus controller should take every setting from HTML, name the parts it touches, and clean up after itself. That lets one controller run in many places on the same page without edits to its JavaScript. The seven rules below come from the Stimulus reference, the outlet and event problems described above, and common practice.

  • Put configuration in values. Declare static values so each instance reads its own settings from data attributes. The select partial does this when it passes the channel in data-select-channel-value. React to a setting in a [name]ValueChanged callback. Stimulus calls it after the controller is initialized and again every time the value changes.
  • Put styling in classes. Declare static classes so each page passes its own CSS class names and the controller never hard codes a class string.
  • Find elements with targets. Use this.[name]Target, and check this.has[Name]Target first when a target is optional, because the singular property throws when nothing matches.
  • Bind events in data-action. Declare actions in the HTML instead of calling addEventListener in connect(), so the wiring sits where the next developer will look for it.
  • Name each instance by its job. Give each instance a target name or a channel prefix that says what it is for, like statesAndProvinces or country, so callers never filter by class.
  • Undo in disconnect() what connect() set up. Timers, window listeners added by hand with addEventListener and third party widgets stay alive after the element goes away. Remove them in disconnect(). Stimulus calls it every time the controller leaves the DOM. A controller that wraps a React component, like the ones in this post, should unmount it in disconnect().
  • Compose small controllers. An element can carry several controllers in one data-controller attribute, so keep each one to a single behavior, and reach for stimulus-use for common ones such as useClickOutside and useDebounce.

The Gnar Company built case-management software for the Massachusetts Disabled Persons Protection Commission, including the commission's abuser registry web application, built in Ruby on Rails and Stimulus.

How do reusable controllers behave across Turbo page visits?#

A reusable controller connects each time Turbo adds its element to the page. Stimulus uses a MutationObserver, so it handles Turbo Drive, Turbo Frames and Turbo Streams like any other DOM update. Turbo Drive restores cached pages on Back. So connect() must be safe to run again on markup it already changed.

The Gnar Company's post Hotwired Modals opens a modal from a target callback when Turbo swaps in an edit form: “In this case, we want the callbacks that activate when a target is connected and disconnected (that is, added to or removed from the children of the controller element).”

MomentWhat Turbo doesWhat the controller should do
LeavingCaches a cloneNode(true) copy, which drops event listenersTear down third-party widgets on turbo:before-cache too
BackRestores that copy without the network, if it canNever let connect() add its markup twice

Conclusion#

In keeping with its ”modest” design goals, Stimulus optimizes for clarity by identifying controllers by their class. In the majority of cases where we’re just adding a bit of dynamism to an otherwise complete page, this makes sense because you can just refer to a controller by what it provides. Reusability is a bit of a curveball because it breaks that assumption: what a bit of UI is no longer identifies what it does, but we don’t have to veer too far from the Stimulus happy path to accommodate it.

Frequently asked questions

Why were outlets awkward for reusable select boxes?

The select boxes shared a controller class but had different purposes. Addressing a particular box through outlets required filtering the boxes and knowing the concrete UI component rather than its role.

How did the target-based approach update a component?

The higher-level controller identified the component's element as a target and dispatched an update event with new props. A shared ComponentController base class listened for that event.

What DOM restriction do targets have?

Targets must be inside their controller's element. The higher-level controller must therefore encompass the components that depend on it.

How can events connect components outside the controller's hierarchy?

Use a custom prefix as a channel name and add @window to the event name to listen outside the controller's hierarchy.

Is Stimulus an alternative to Material UI?

No. Stimulus is a small JavaScript framework that adds behavior to HTML your server already renders, while Material UI is a React component library that implements Google's Material Design. The two can work together, because a Stimulus controller can wrap a React component. In the project this post describes, Stimulus controllers wrapped React components and sent them new props through a custom update event.

How do you start using Stimulus?

Install @hotwired/stimulus. Write a controller class that extends Controller. Start an Application and register the controller under its identifier, or let stimulus-rails autoload it. Then attach it to an element with a data-controller attribute. The handbook starts with three core concepts: controllers, actions that bind events in data-action attributes, and targets that name the elements a controller touches. The official Stimulus handbook covers each one in order.

What is stimulus-use?

stimulus-use is a community collection of composable behaviors for Stimulus controllers, kept separate from Stimulus itself. It adds helpers such as useClickOutside, useDebounce, useIntersection and useResize, so a reusable controller can gain a common behavior without hand written listener code.

How do you set a custom prefix when dispatching a Stimulus event?

Pass it in the options object, the second argument to this.dispatch. For example, this.dispatch('select', { prefix: this.channelValue, detail: { value } }) sends an event named after the channel, such as country:select. The prefix defaults to the controller's identifier, and a false or null prefix sends the bare event name.

Stay In The Loop

Never miss an update. Get the latest blogs, webinars, and expert insights straight to your inbox from The Gnar.