skip to content

Stimulus Controllers & Actions

Stimulus attaches small JavaScript controllers to server-rendered HTML through controller, action and target attributes. Interviewers check that you keep state in the DOM.

on this pageshow

explore

questions

5

In Stimulus, how do the data-controller, data-action and data-<identifier>-target attributes connect server-rendered HTML to a controller class?

level: juniorimportance: must knowfreq 72%

answer

  1. three attributes, one controller class
  2. file name becomes the identifier
  3. event->identifier#method
  4. static targets gives three properties
  5. singular target throws when missing

basics

~10 s

data-controller names an identifier, so Stimulus attaches that controller class to the element; data-action routes a DOM event to a controller method; data-<identifier>-target names elements the controller reads through generated properties such as this.sourceTarget.

solid answer

~40 s

Stimulus watches the document for `data-controller` attributes. Each space-separated identifier in one, such as `copy-link`, gets an instance of the controller class registered under that name; in a Rails app the name comes from the file, so `copy_link_controller.js` becomes `copy-link`. `data-action="click->copy-link#copy"` installs a listener that calls `copy(event)` on that instance. Elements marked `data-copy-link-target="source"` become reachable once the class declares `static targets = ["source"]`: Stimulus generates `this.sourceTarget` (the first match, throwing if there is none), `this.sourceTargets` (all matches) and `this.hasSourceTarget`. Everything is scoped to the controller's element and its descendants, and the state lives in the HTML the server rendered rather than in a client-side template.

code

html · 6 lines
html
<div data-controller="copy-link">
  <input type="text" readonly
         value="https://jobs.example.com/postings/42"
         data-copy-link-target="source">
  <button type="button" data-action="copy-link#copy">Copy link</button>
</div>

go deeper

for a junior

Recall the three attributes, the arrow syntax of an action, and how a file name like copy_link_controller.js becomes the identifier copy-link.

for a middle

Explain the three generated target properties, which one throws, and how scope excludes elements inside a nested controller with the same identifier.

for a senior

Show why keeping state in server-rendered HTML lets controllers survive Turbo body swaps, cache restores and morphs, and spot the deprecated data-target form in old views.

for a principal

Frame Stimulus as decoration of server HTML rather than a rendering layer, and judge when a screen's state has outgrown attributes and targets.

## Three attributes, one contract **Stimulus** is the JavaScript half of Hotwire. It does not render HTML. The server (in a Rails app, an ERB view) renders ordinary markup, and Stimulus attaches small **controllers** to it through three attribute families: - **`data-controller`** names which controller classes own an element; - **`data-action`** routes DOM events to methods on those controllers; - **`data-<identifier>-target`** names the elements a controller needs to read or change. Because the contract lives in attributes, the same controller keeps working when Turbo replaces the page body, loads a frame or applies a stream: Stimulus observes the document with a `MutationObserver` and connects whatever appears. ## Identifiers: the name in the HTML An **identifier** is the string inside `data-controller`. In a Rails app it is derived from the file path under `app/javascript/controllers/`: | controller file | identifier | |---|---| | `copy_link_controller.js` | `copy-link` | | `character_counter_controller.js` | `character-counter` | | `job_postings/copy_link_controller.js` | `job-postings--copy-link` | Underscores become dashes, a subdirectory becomes a double dash, and the `_controller` suffix is dropped. The exported class name plays no part; outside the Rails loaders you call `application.register("copy-link", CopyLinkController)` yourself. One element can carry several identifiers, as in `data-controller="copy-link character-counter"`, and each gets its own instance. ## Actions: events to methods `data-action="click->copy-link#copy"` is an **action descriptor**: the event name, the identifier and the method name. When the event fires, Stimulus calls `copy(event)` on the instance whose identifier matches. The descriptor has more syntax (default events, key filters, global targets, options, parameters), but the core is that one arrow. The action must sit on the controller's element or inside it: a descriptor naming a controller that is not on an ancestor never fires. ## Targets: named elements A controller lists its target names in a static array, and Stimulus generates three properties per name: | property | returns | |---|---| | `this.sourceTarget` | the first matching element in scope; **throws** `Missing target element "source" for "copy-link" controller` if there is none | | `this.sourceTargets` | an array of every match, possibly empty | | `this.hasSourceTarget` | a boolean, for optional targets | The attribute is `data-copy-link-target="source"`, and its value is a space-separated list, so one element can be several targets, or targets of several controllers at once. ## Scope: what a controller can see A controller's **scope** is its own element plus its descendants, minus anything inside a nested element carrying the **same** identifier. Two copy-link widgets on one job listing therefore never see each other's `source` targets, even when one sits inside the other. Targets elsewhere on the page are invisible; reaching another controller goes through outlets or events, which are a separate topic. ## Keeping state in the HTML The design point interviewers probe is where state lives. A Stimulus controller reads what it needs from the DOM (a target's value, an attribute) and writes its results back into the DOM (text, classes, attributes). Nothing is rendered from a JavaScript template, and nothing important lives only in a JavaScript variable, so a server re-render, a Turbo cache restore or a morph leaves the page consistent. A copy-link button on a job posting shows the whole contract: 1. The view renders a read-only input holding the posting URL with `data-copy-link-target="source"`. 2. The wrapper carries `data-controller="copy-link"`. 3. The button carries `data-action="copy-link#copy"` (a button's default event is `click`). 4. `copy()` reads `this.sourceTarget.value` and writes it to the clipboard. ## Mistakes that fail quietly Several wiring errors produce no exception at all, which is why they come up in interviews: - **An identifier typo** (`data-controller="copylink"`) matches no registered controller, so nothing connects and nothing is logged. - **A target name missing from `static targets`** generates no property: `this.sourceTarget` is plain `undefined`, and the error you see is a `TypeError` on the next line rather than Stimulus' missing-target message. - **Dashed target names** such as `data-copy-link-target="source-field"` produce no usable `this.…Target` property; the docs require camelCase because target names become property names. - **An action outside the controller's element** never binds, because each controller only observes `data-action` attributes inside its own scope. ## The retired syntax Before Stimulus 2, targets were written `data-target="copy-link.source"`. Stimulus 3.2.2 still resolves that form but logs a deprecation warning asking for `data-copy-link-target="source"`, and new code should use only the scoped attribute.

  • What happens if the template forgets the element a controller reads through this.sourceTarget?
    The singular getter throws an error naming the missing target and the controller, so the method stops there. `this.sourceTargets` would return an empty array instead, and `this.hasSourceTarget` returns `false`. For a target that is genuinely optional, guard with `hasSourceTarget` before touching the singular property.
  • Can one element carry two controllers and be a target of both?
    Yes. `data-controller` holds a space-separated list of identifiers, and each gets its own instance on the same element. An element can also carry `data-copy-link-target` and `data-character-counter-target` side by side, and each target attribute may list several names.
  • You meet data-target="copy-link.source" in an old view. What do you change?
    That is the pre-Stimulus-2 target syntax. Stimulus 3.2.2 still finds the element but logs a deprecation warning. Rewrite it as `data-copy-link-target="source"`, the scoped attribute the current target lookup uses.

  • Stimulus renders the controller's markup from a client-side template
  • The identifier comes from the class name the module exports
  • this.sourceTarget returns undefined when no source element exists
  • A controller can read targets anywhere on the page, not just inside its element
  • data-target="copy-link.source" is the current target syntax in Stimulus 3

Assumes Stimulus 3.2.2 (stimulus-rails 1.3.4) beside Turbo 8; the legacy data-target="identifier.name" form still resolves there but logs a deprecation warning.

open as a page

In a Stimulus data-action descriptor, what do default events, key filters, @window and the :prevent, :stop and :once options change?

level: middleimportance: should knowfreq 48%

basics

~20 s

A descriptor may omit the event for common elements (textarea means input, form means submit), filter keyboard events (keydown.ctrl+enter), listen on window or document (@window), and add options: :prevent and :stop call preventDefault or stopPropagation, :once passes once to addEventListener.

open as a page

In Stimulus, how do action parameters such as data-copy-link-url-param reach a controller method, and how are their values typecast?

level: middleimportance: should knowfreq 38%

basics

~20 s

Stimulus reads data-<identifier>-<name>-param attributes from the element carrying the action, camelizes the names and passes them as event.params; each value goes through JSON.parse, so numbers, booleans and objects arrive typed and anything unparsable stays a string.

open as a page

In a Rails 8.1 import-map app, how does eagerLoadControllersFrom in controllers/index.js register Stimulus controllers, and when does lazyLoadControllersFrom fit better?

level: middleimportance: should knowfreq 30%

basics

~20 s

eagerLoadControllersFrom reads the page's import map, imports every pin under controllers/ ending in _controller and registers each under an identifier derived from its path. lazyLoadControllersFrom imports a controller only when its identifier first appears in a data-controller attribute.

open as a page

A Stimulus character counter inserts its counter element and starts a setInterval in connect(); after Turbo visits and Back-button restores, counters duplicate and timers pile up. Why, and how do you fix it?

level: seniorimportance: should knowfreq 42%

basics

~20 s

Each Turbo visit or cache restore brings new elements and new controller instances; the cached snapshot already holds the counter connect() inserted, and old intervals were never cleared. Server-render the counter, keep connect() idempotent, clear timers in disconnect().

open as a page