
Rails 7: Stimulus JS Basics
1. Picky about Naming when setting up Controller.
When setting up the controller, there must be a ‘data-controller’ attribute that matches the name of the controller. in the case of a two-word controller, you’ll use dashes in the views and underscores in the name of the file.
Remember, the name of the actual Javascript object does not appear in the file itself– it is inferred by the file name.
Consider for example a very simple Stimulus controller.
controllers/know_nothing_controller.js
import { Controller } from "stimulus"
export default class extends Controller {
connect() {
}
}
Here it is in my IDE shown as a file ending with extension .js
:


2. Picky about Target Naming
Let’s consider a basic target naming example
Target naming with Two Words
import { Controller } from "stimulus"
export default class extends Controller {
static targets = [ "abcXyz" ]
connect() {
this.abcXyzTarget.classList.add("pop")
}
}
Our template (view) will look like this:

Notice tat for the data attribute we use data-
then the name of the controller -target
. Here, always use dashes.
For the target name itself, there is no dash-to-camelCase conversion, so for two-word targets refer to the target by camelCase in the target name in the view (above) and also in the javascript (below)

3 Data actions
'data-action' => "click->video#show_and_play"
Remember these are in this order
JS ACTION (CLICK), ARROW, CONTROLLER NAME, POUND, METHOD NAME
click->video#show_and_play