skip to content

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%

answer

  1. data-identifier-name-param
  2. same element as the data-action
  3. event.params, names camelized
  4. JSON.parse, else the raw string
  5. leading zeros stay strings

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.

solid answer

~40 s

Action parameters let one controller serve many triggers. On the element that carries `data-action="copy-link#copy"` you add attributes like `data-copy-link-url-param` and `data-copy-link-posting-id-param`. When the action fires, Stimulus collects every `data-copy-link-*-param` attribute on that same element (not its ancestors), camelizes the names and attaches them to the event, so the method can destructure `{ params: { url, postingId } }`. Params for other identifiers on the element are ignored. Each value is run through `JSON.parse`: `"42"` becomes the number 42, `"true"` a boolean, `'{"a":1}'` an object, and a value JSON rejects, such as a URL or `0042`, is passed as the original string. The attributes are re-read on every event.

code

erb · 11 lines
erb
<ul data-controller="copy-link">
  <% @job_postings.each do |posting| %>
    <li>
      <%= posting.title %>
      <%= button_tag "Copy link", type: "button",
            data: { action: "copy-link#copy",
                    copy_link_url_param: job_posting_url(posting),
                    copy_link_posting_id_param: posting.id } %>
    </li>
  <% end %>
</ul>

go deeper

for a junior

Recall the data-identifier-name-param shape and that the method reads the values from event.params.

for a middle

Explain that params come only from the action's own element, are camelized, are filtered by identifier and are typecast through JSON.parse with a string fallback.

for a senior

Spot type drift from JSON parsing, such as ids that switch between Number and String or lose precision, and choose params versus values deliberately.

for a principal

Use params to keep one controller generic across many server-rendered rows, keeping identifiers and URLs owned by the view rather than duplicated in JavaScript.

## What action parameters are for A list of job postings often needs the same behaviour on every row: a **copy link** button per posting. Rather than one controller per row, a single `copy-link` controller on the list can serve every button if each button tells the method **which** posting it belongs to. **Action parameters** carry that per-trigger data. ## The attribute format A parameter is a data attribute on the element that carries the action: ``` data-<identifier>-<param-name>-param="value" ``` - `<identifier>` must be the identifier in the action's descriptor (`copy-link` for `copy-link#copy`). - `<param-name>` is written in kebab-case and arrives camelized: `posting-id` becomes `postingId`. - The attribute must sit on the **same element** as the `data-action`. Stimulus does not look at ancestors, so a param on the surrounding `<li>` is invisible to a button's action. - Params for another identifier on the same element are left out, so `copy-link#copy` and `analytics#track` on one button each see only their own. ## How the method receives them Stimulus extends the DOM event with a `params` object just before calling the method: ```javascript copy({ params: { url, postingId }, currentTarget }) { navigator.clipboard.writeText(url) currentTarget.textContent = `Copied #${postingId}` } ``` The attributes are read **every time** the event fires, so a param changed by a Turbo Stream or by other code is picked up on the next click without reconnecting anything. ## Typecasting Each value goes through `JSON.parse`; if that throws, the raw string is used: | attribute value | `params` value | type | |---|---|---| | `42` | `42` | Number | | `true` | `true` | Boolean | | `{"title":"Rails developer"}` | an object | Object | | `[1,2]` | an array | Array | | `https://jobs.example.com/postings/42` | the same text | String | | `0042` | `"0042"` | String (JSON rejects leading zeros) | | `"42"` (quotes inside the attribute) | `"42"` | String | Two consequences matter in practice: 1. **Types depend on content.** Reference codes such as `1234` and `0042` arrive as a Number and a String respectively. If a value must always be a string, write it as a JSON string, with quotes inside the attribute. 2. **Large integers lose precision.** Digits beyond JavaScript's safe-integer range (2^53 - 1) are rounded by `JSON.parse`; pass such ids as JSON strings. ## Mistakes that leave params empty - **The param sits on the wrong element.** It must be on the element with `data-action`, not the row, the list or the controller's element. - **The identifier does not match.** `data-clipboard-url-param` is invisible to a `copy-link#copy` action; the prefix must be the action's own identifier. - **The method is called directly.** `params` is attached only when Stimulus dispatches the action; calling `this.copy(event)` from another method passes whatever event you hand it. - **The data is secret.** Params are plain attributes in the page source, so anything a viewer must not see belongs on the server, not in a param. ## Rendering params from Rails Rails' tag helpers dasherize the keys of a `data:` hash, so `data: { action: "copy-link#copy", copy_link_url_param: job_posting_url(posting) }` on a `button_tag` renders `data-copy-link-url-param`. The view stays the single source of the URL, and the controller holds no lookup tables. ## Params versus values Both come from data attributes, but they answer different questions: - a **param** belongs to one action's trigger element and arrives with that event; - a **value** belongs to the controller's element, is declared in `static values` with a type and default, and can notify the controller when it changes. Per-button data is a param; controller-wide configuration is a value. Values have their own declaration rules and callbacks, covered separately.

  • When would you reach for a Stimulus value instead of an action param?
    When the data describes the controller rather than one trigger: a maximum length, an endpoint, a mode. Values live on the controller's element, are declared with a type and default, and can fire a change callback. Params suit per-button data such as which posting a copy button points to.
  • A posting id of 9007199254740993 arrives as 9007199254740992. Why, and what is the fix?
    Stimulus parses param values with `JSON.parse`, which turns the digits into a JavaScript Number, and that number is beyond the safe-integer range, so it rounds. Render the id as a JSON string with quotes inside the attribute, and the param arrives as the exact string.

  • Action params can sit on an ancestor of the element with data-action
  • Params always arrive as strings, exactly like dataset values
  • event.params holds every param on the element, whatever its identifier
  • Params are read once, when the controller connects
  • A param named posting-id is read as params["posting-id"]