Matt Buck: Founder & Full-stack Engineer

Using Rails UJS Confirmations in Stimulus and StimulusReflex

One of the many benefits of using the fantastic StimulusReflex has been a return to using the conventions of Rails UJS. Simply appending a data attribute to an element to have it automatically disable itself during an interaction is the type of magic that reminds me of first getting started with Rails.

If you need to add a confirmation step to an interaction, which is a common pattern if a user is trying to destroy an object, you can make use of the data-confirm attribute:

<button data-confirm="Are you sure you want to remove this context?">
  <%= render_svg 'icons/custom/remove' %>
</button>

If you try to use data-confirm with Stimulus or StimulusReflex, you’ll find out that data-confirm is not supported out-of-the-box - which makes sense. In order to use it along with data-action or data-reflex, you can simply listen for the confirm:complete event (instead of click) that is triggered by rails-ujs when the user accepts the confirmation modal:

<button data-reflex-dataset="combined"
        data-confirm="Are you sure you want to remove this context?"
        data-reflex="confirm:complete->Context#remove_context">
  <%= render_svg 'icons/custom/remove' %>
</button>
// When confirmation accepted, delete the block.
this.element.addEventListener("confirm:complete", (event) => {
  this.stimulate("ScriptEditor#delete_context", event.target);
});

user accepting a confirmation modal

Now, the action specified by data-action or data-reflex will only be triggered if the user accepts the confirmation dialog. This allows us to easily add a confirmation step to any Stimulus or StimulusReflex interaction.


I ran across this issue while building Voxable, a conversation design platform. If you’re building chatbots or voice applications, I hope you’ll check it out!