# Terminal
rails webpacker:install:stimulus
yarn install
bin/webpack-dev-server
# package.json
"stimulus": "^2.0.0",
# welcome/index.html.erb
<div data-controller="hello" data-hello-number-value=4>
<%# <h1 data-target="hello.output"></h1> %>
<h1 data-hello-target='output'></h1>
<button data-action='hello#clicked'>CLICK ME</button>
</div>
<div data-controller="text-input">
<input type="text" data-action="text-input#changed" data-text-input-target="input">
<h1 data-text-input-target='output'></h1>
</div>
<div data-controller="styling"
data-styling-primary-class="btn-primary">
<button class='btn' data-styling-target='button' data-action='styling#clicked'>
CLICK ME
</button>
</div>
<div data-controller="styling"
data-styling-primary-class="btn-primary">
<button class='btn' data-styling-target='button' data-action='styling#clicked'>
CLICK ME
</button>
<button data-action="styling#clicked:once">CLICK ONCE</button>
</div>
# javascript/controllers/hello_controller.js
import { Controller } from "stimulus"
export default class extends Controller {
static targets = [ "output" ]
static values = { number: Number }
connect() {
this.numberValueChanged()
}
clicked() {
this.numberValue++
}
numberValueChanged() {
this.outputTarget.textContent = this.numberValue
}
}
# javascript/controllers/styling_controller.js
import { Controller} from "stimulus"
export default class extends Controller {
static targets = ["button"]
static classes = ["primary"]
connect() {
this.buttonTarget.classList.add(this.primaryClass)
}
clicked() {
this.buttonTarget.classList.toggle(this.primaryClass)
}
}
# javascript/controllers/text_input_controller.js
import { Controller} from "stimulus"
export default class extends Controller {
static targets = ["input", "output"]
connect() {}
changed() {
this.outputTarget.textContent = this.inputTarget.value
}
}