This component is available on GitHub.
Stimulus Remote Rails
A Stimulus controller to handle Rails UJS events.
Installation
$ yarn add stimulus-remote-rails
And use it in your JS file:
// Probably in app/javascript/controllers/index.js
import { Application } from '@hotwired/stimulus'
import Remote from 'stimulus-remote-rails'
const application = Application.start()
application.register('remote', Remote)
π Demo
See demo βUsage
In your controller:
class CommentsController < ApplicationController
def create
@comment = Comment.new(comment_params)
if @comment.save
render @comment
else
render partial: 'comments/form', locals: { comment: @comment }, status: :unprocessable_entity
end
end
private
def comment_params
params
.require(:comment)
.permit(:content)
end
end
In your view:
<%= form_with model: @comment, data: { controller: 'remote', action: 'ajax:success->remote#append ajax:error->remote#replace' } do |f| %>
<% if f.object.errors.any? %>
<% f.object.errors.full_messages.each do |error| %>
<p><%= error %></p>
<% end %>
<% end %>
<%= f.label :content %>
<%= f.text_field :content %>
<%= f.submit 'Save comment' %>
<% end %>
With a link_to
:
<%= link_to 'Click me to append content', content_path, remote: true, data: { controller: 'remote', action: 'ajax:success->remote#append' } %>
<%= link_to 'Click me to prepend content', content_path, remote: true, data: { controller: 'remote', action: 'ajax:success->remote#prepend' } %>
<%= link_to 'Click me to replace content', content_path, remote: true, data: { controller: 'remote', action: 'ajax:success->remote#replace' } %>
You can use append
, prepend
or replace
methods with the events of your choice.
Don't forget to add the remote: true
attribute in your link_to
!
You can use it with all remote elements available in Rails UJS.
π Extending Controller
You can use inheritance to extend the functionality of any Stimulus component:
import Remote from 'stimulus-remote-rails'
export default class extends Remote {
connect() {
super.connect()
console.log('Do what you want here.')
}
}
This controller will automatically have access to targets defined in the parent class.
If you override the connect
, disconnect
or any other methods from the parent, you'll
want to call super.method()
to make sure the parent functionality is executed.
βοΈ Sponsors
Stimulus Component is an MIT licensed open source project and completely free to use. However, the amount of effort needed to maintain and develop new features for the project is not sustainable without proper financial backing. You can support Stimulus Components development on Github Sponsors. π
π· Contributing
Do not hesitate to contribute to the project by adapting or adding features ! Bug reports or pull requests are welcome.
Donβt forget to drop a π on Github to support the project.
π License
This project is released under the MIT license.