The Stimulus 2.0 Tutorial

Episode #272 by Teacher's Avatar David Kimura

Summary

Stimulus 2.0 has been released and with it comes new features, changes and bug fixes. In this episode, we look at adding Stimulus in our application, exploring the new features, and looking at what has changed.
javascript rails stimulusjs 16:29

Resources

Summary

# 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
  }
}