DEV Community

loading...
Cover image for Using Rails UJS Confirmations in Stimulus and StimulusReflex

Using Rails UJS Confirmations in Stimulus and StimulusReflex

Matt Buck
I make machines talk.
・2 min read

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>
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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!

Discussion (2)

Collapse
coderberry profile image
Eric Berry

Thank you!

Collapse
leo123 profile image
Leo • Edited

For me, it gets called whether the user accepts or not.

Forem Open with the Forem app