Stimulus HelpersLink to heading

Stimulus data attributes can be a bit verbose, so LiveComponent features a few helper methods to make them easier to read and write.

Action attributesLink to heading

Stimulus action attributes generally take the form data-action="event->controller#method". Use LiveComponent's on method to attach a data attribute with a friendlier syntax:
<%= render(
  ButtonComponent.new(
    actions: on(:click).call(:my_click_handler)
  )
) %>
<%= render(
  ButtonComponent.new(
    actions: on(:click).call(:my_click_handler)
  )
) %>
In the example above, clicking the button will call a method named my_click_handler on the associated live controller. LiveComponent will transform the returned LiveComponent::Action into a hash of data attributes, which will then be passed into the component. The ButtonComponent must handle emitting the data attributes into the rendered HTML.

Target attributesLink to heading

Stimulus target attributes generally take the form data-controller-target="name", where "controller" is the name of the associated live controller. Use LiveComponent's target method to attach a data attribute with a friendlier syntax:
<%= render(ButtonComponent.new(targets: target(:submit_button))) %>
<%= render(ButtonComponent.new(targets: target(:submit_button))) %>
In the example above, the button will be passed a hash with a "data-buttoncomponent-target" => "submit_button" pair. The ButtonComponent must handle emitting the data attributes into the rendered HTML.See the action documentation above for an example of how to emit data attributes.

Rails tag helpersLink to heading

LiveComponent patches Rails, making it possible to pass actions: and targets: as attributes to the content_tag, button_to, and form_with helpers.
<%= content_tag(actions: on(:click).call(:my_method)) %>
<%= content_tag(actions: on(:click).call(:my_method)) %>