Add Stimulus JS to a Rails 6 app
Published: 2021-01-19
Intro
Stimulus JS is a "A modest JavaScript framework for the HTML you already have." The aim of the project is to sprinkle your webapp with Javascript to load dynamic content as opposed to building your entire frontent with JS.
In this post I will cover the process of installing and getting started with StimulusJS in a Rails 6 app.
Software Used
The following software was used in this post.
- Rails - 6.0.3.4
- Stimulus - 2.0.0
Installation
Install Stimulus with the
bundle exec rails webpacker:install:stimulus
bundle exec rails webpacker:install:stimulus
# output
Installing all Stimulus dependencies...[output truncated for brevity]
This will install Stimulus and also in typical rails fashion the following boilerplate files/folders will be created.
- app/javascript/controllers
- app/javascript/controllers/hello_controller.js
- app/javascript/controllers/index.js
Usage
I will use the example code from the Stimuls website for the next section.
At the time of writing the code for the hello_controller.js file generated by the install process was not compatible with the example code from the website.
Change the file to the following contents.
# app/javascript/controllers/hello_controller.js
import { Controller } from "stimulus"
export default class extends Controller {
static targets = [ "name", "output" ]
greet() {
this.outputTarget.textContent =
`Hello, ${this.nameTarget.value}!`
}
}
In some view add the following example content.
# app/views/examples/index.html.erb
<!--HTML from anywhere-->
<div data-controller="hello">
<input data-hello-target="name" type="text">
<button data-action="click->hello#greet">
Greet
</button>
<span data-hello-target="output">
</span>
</div>
This will create an input like the below.
Type something in the box and press the Greet button.
If everything is setup correctly you will see some output next to the input box.
If not, open the inspector console in your browser and check for any errors.
Outro
In this post I covered the process of installing and using Stimulus JS in a Rails 6 application. Do you feel stimulated? I know I do!
Links
https://www.digitalocean.com/community/tutorials/how-to-add-stimulus-to-a-ruby-on-rails-application
https://medium.com/swlh/build-a-dynamic-search-with-stimulus-js-and-rails-6-56b537a44579